1

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?

ap0
  • 1,083
  • 1
  • 12
  • 37
  • possible duplicate of [Python: Difference between class and instance attributes](http://stackoverflow.com/questions/207000/python-difference-between-class-and-instance-attributes) – sebastian Oct 30 '14 at 13:34
  • 1
    Also, check the answers at http://stackoverflow.com/questions/2923579/python-class-attribute and http://stackoverflow.com/questions/68645/static-class-variables-in-python. Each instances of Foo1 can access (and share) `something` with `x.__class__.something` – fredtantini Oct 30 '14 at 13:34
  • Yet another: http://stackoverflow.com/q/206734/2319400 – sebastian Oct 30 '14 at 13:36
  • Thank you. Sorry if this is a duplicate. I was missing the right terminology to look for an answer correctly. – ap0 Oct 30 '14 at 13:36

2 Answers2

3

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

Tamim Shahriar
  • 739
  • 4
  • 9
2

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
anon582847382
  • 19,907
  • 5
  • 54
  • 57