Attribute definition, WHY?

Donn Cave donn at u.washington.edu
Tue Sep 12 14:25:52 EDT 2000


Quoth bragib at my-deja.com:
| 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?

Yes, and perils.  As another followup already explains, attributes
defined in the class scope are shared by all instances.  It's a
useful thing, but apt to surprise you if you don't know Python well.

What happens if you combine the two class A examples, assigning an
attr1 in the class A definition and then again in __init__()?

There's the rub.  Not everyone knows Python that well, and even
if you do, it might be easy to make a mistake if you forget that
you have done this.  So you'll probably still want to use this
feature, but maybe with some restraint.  In my own work, I use
it most often with constants.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list