Attribute definition, WHY?

Matthew Dixon Cowles matt at mondoinfo.com
Tue Sep 12 14:16:12 EDT 2000


On Tue, 12 Sep 2000 17:17:42 GMT, bragib at my-deja.com
<bragib at my-deja.com> wrote:

>Why would you want to do the following:
>
>class A:
>   attr1 = [1,2]
>   def __init__(self,name):
>       self.name = name
>
>and not
>
>class A:
>   def __init__(self,name):
>       self.name = name
>       self.attr1 = [1,2]
>
>Are there benefits to the first definition?

Bragi,
In the first definition, the value of attr1 is shared by the whole
class. That's useful for counters and whatnot. So, given the first
definition, code like this:

foo=A('foo')
bar=A('bar')
A.attr1=[3,4]
print foo.attr1
print bar.attr1

would produce

[3, 4]
[3, 4]

Regards,
Matt



More information about the Python-list mailing list