instance

Setting default/empty attributes for user classes in __init__

Setting default/empty attributes for user classes in __init__ Question: When I am creating a new class, should I set all instance attributes in __init__, even if they are None and in fact later assigned values in class methods? See example below for the attribute results of MyClass: class MyClass: def __init__(self,df): self.df = df self.results …

Total answers: 4

django – TypeError how to get instance of a foreignkey from the user instance

django – TypeError how to get instance of a foreignkey from the user instance Question: I am getting the following type error and its due to this instance in view. The model as you can see below where Employee is onetoone relation to User and Company is the foreignkey to the Employee. How would I …

Total answers: 1

Python : class definition with **kwargs

Python : class definition with **kwargs Question: When trying to instantiate the following class I am getting the following error : “TypeError: __init__() takes exactly 2 arguments (3 given)” Do you know what would be the issue ? Here is the class definition : class db_create_table(): ”’ doc here ”’ def __init__(self,TableName, **kwargs ): self.TableName …

Total answers: 4

Python Classes ( AttributeError: '' object has no attribute '')

Python Classes ( AttributeError: '' object has no attribute '') Question: Having trouble understanding the problem in my code, new to classes (generally python too, so sorry if I name things wrong). I receive this error: I think my code is too long winded to include in here, so I made a simplified version to …

Total answers: 4

Why won't dynamically adding a `__call__` method to an instance work?

Why won't dynamically adding a `__call__` method to an instance work? Question: In both Python 2 and Python 3 the code: class Foo(object): pass f = Foo() f.__call__ = lambda *args : args f(1, 2, 3) returns as error Foo object is not callable. Why does that happen? PS: With old-style classes it works as …

Total answers: 2

Create an anonymous class instance in python

Create an anonymous class instance in python Question: Sometimes I need to create an anonymous class instance in python, just like c#: var o = new {attr1="something", attr2=344}; but in python I do it in this way: class Dummy: pass o = Dummy() o.attr1 = ‘something’ o.attr2 = 344 # EDIT 1 print o.attr1, o.attr2 …

Total answers: 5

How to keep track of class instances?

How to keep track of class instances? Question: Toward the end of a program I’m looking to load a specific variable from all the instances of a class into a dictionary. For example: class Foo(): def __init__(self): self.x = {} foo1 = Foo() foo2 = Foo() … Let’s say the number of instances will vary …

Total answers: 7