Reputation: 1173
Two examples;
class Foo1:
something = 0
def __init__(self, n):
self.something = n
and
class Foo2:
def __init__(self, n):
self.something = n
Both classes seem to have the same behaviour:
x = Foo1(42)
y = Foo2(36)
print x.something
# will print 42
print y.something
# will print 36
But in the class Foo1
is the variable self.something
(in the constructor) actually the variable something
as defined at the beginning of the class? What is the difference here? Which way is preferred to use?
Upvotes: 1
Views: 105
Reputation: 20351
something
is not the same as self.something
. When you access x.something
or y.something
, you are accessing the version that is bound to that instance. The original something
is local to that type
rather than an object from that type:
>>> Foo1.something
0
>>> Foo1(42).something
42
Upvotes: 2
Reputation: 739
The difference is, in the first case, you can access the data attribute without using an object (or instance). In the second case, you can't. Please check the following code snippet :
>>> class Foo1:
... something = 0
... def __init__(self, n):
... self.something = n
...
>>> Foo1.something
0
>>> class Foo2:
... def __init__(self, n):
... self.something = n
...
>>> Foo2.something
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: class Foo2 has no attribute 'something'
>>>
Hope I could clarify. For more, please read this : https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables
Upvotes: 3