Hope you guys are doing good and have enjoyed the weekend so far.
I had a doubt with classes, creating an instance of a class means to call the class and assign it to a variable?
for e.g.: Class abc(object):
def init(self, type):
self.letter = type
input_string = abc(). - So, this is where am creating the instance of the class or is it next line?
print input_string.letter
We are the designers, so it’s not about whether something should or shouldn’t be there, but whether we want it there, and for whatever reason. Classes that have no __init__ method will only give methods and class variables to their instances.
>>> class foo:
bar = 'bar'
def __repr__(self):
return "Foo has no instance attributes."
def set(self, foo):
self['foo'] = foo
def get(self):
return self.bar
>>> bar = foo()
>>> bar.get()
'bar'
>>> bar
Foo has no instance attributes.
>>> bar.set('foo')
Traceback (most recent call last):
File "<pyshell#582>", line 1, in <module>
bar.set('foo')
File "<pyshell#578>", line 6, in set
self['foo'] = foo
TypeError: 'foo' object does not support item assignment
>>>
Not to make any points with the above. Take the examples for what they are.
Classes without __init__ do not have to be instantiated. We can call the methods directly on the class, as we saw with variables, above.
Note that just because a class does not have an __init__ method doesn’t mean the instance doesn’t inherit one. Look to the super class to see if the method does in fact exist. It might be that instance parameters are still required by the class the instances inherit from.