Classes in Python
Fernando Perez
fperez528 at yahoo.com
Fri Apr 18 15:25:40 EDT 2003
Bill Martin wrote:
> I'm wondering about the value of allowing a class definition like this:
>
> class C:
> pass
>
> Now I can define a = c() and b = c(), then say a.x1 = 1.2, b.x2 = 3.5 or
> some such. If I try to print a.x2 or b.x1, I get an exception message
> basically saying those member variables don't exist. It seems to me this
> defeats one of the basic ideas behind OOP, that is to assign members to
> the class definition, thus ensuring that all instantiations of a class
> have the same member variables and methods. I know there must be a
> reason that python allows this kind of thing that I described, but I
> can't figure out what that reason could be. To me, it looks like a very
> dangerous thing to do. Can someone help me understand why we'd like to
> do it? Thanks,
You are confusing the class and its instances. a.x1 assigns to a's private
dict, so b can't see the x1 attribute, as it shouldn't.
If you want all instances of a class to see something, you must assign it to
the class:
In [1]: class C:
...: pass
...:
In [2]: a=C()
In [3]: b=C()
In [4]: a.x1='in a'
In [5]: b.x2='in b'
In [6]: C.y='in all'
In [7]: a.x1
Out[7]: 'in a'
In [8]: b.x2
Out[8]: 'in b'
In [9]: a.x2
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
?
AttributeError: C instance has no attribute 'x2'
In [10]: b.x1
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
?
AttributeError: C instance has no attribute 'x1'
In [11]: a.y
Out[11]: 'in all'
In [12]: b.y
Out[12]: 'in all'
No surprises here. Classes and instances are two different things.
hth,
f.
More information about the Python-list
mailing list