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?

4

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Would this be pythons equivalent to static variables in C?
I don't think C static variable concept is required for Python.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.