views:

1499

answers:

4

Is there any meaningful distinction between:

class A(object):
    foo = 5   # some default value

vs.

class B(object):
    def __init__(self, foo=5):
        self.foo = foo

If you're creating a lot of instances, is there any difference in performance or space requirements for the two styles? When you read the code, do you consider the meaning of the two styles to be significantly different?

+13  A: 

Beyond performance considerations, there is a significant semantic difference. In the class attribute case, there is just one object referred to. In the instance-attribute-set-at-instantiation, there can be multiple objects referred to. For instance

>>> class A: foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[5]
>>> class A:
...  def __init__(self): self.foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo    
[]
fivebells
A: 

As per the comment of Dan:

Similar question which has been answered: Why do attribute references act like this with python inheritance

ΤΖΩΤΖΙΟΥ
+1  A: 

Just an elaboration on what Alex Coventry said, another Alex (Martelli) addressed a similar question on the comp.lang.python news group years back. He examines the symantic difference of what a person intended vs what he got (by using instance variables).

http://groups.google.com/group/comp.lang.python/msg/5914d297aff35fae?hl=en

torial
+1  A: 

The difference is that the attribute on the class is shared by all instances. The attribute on an instance is unique to that instance.

If coming from C++, attributes on the class are more like static member variables.

Peter Shinners