Suppose I have this code:
class Example(object):
def the_example(self):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
When I try it, I get an error that says:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Example' object has no attribute 'itsProblem'
How do I access this attribute? I tried adding another method to return it:
def return_itsProblem(self):
return itsProblem
but the problem persists.
The answer, in a few words
In your example,
itsProblemis a local variable.Your must use
selfto set and get instance variables. You can set it in the__init__method. Then your code would be:But if you want a true class variable, then use the class name directly:
But be careful with this one, as
theExample.itsProblemis automatically set to be equal toExample.itsProblem, but is not the same variable at all and can be changed independently.Some explanations
In Python, variables can be created dynamically. Therefore, you can do the following:
prints
Therefore, that’s exactly what you do with the previous examples.
Indeed, in Python we use
selfasthis, but it’s a bit more than that.selfis the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call itselfor not.Which means you can do:
or:
It’s exactly the same. The first argument of ANY object method is the current object, we only call it
selfas a convention. And you add just a variable to this object, the same way you would do it from outside.Now, about the class variables.
When you do:
You’ll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?
Well, Python tries to get first the object variable, but if it can’t find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.
As a conclusion, never use class variables to set default values to object variables. Use
__init__for that.Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.