Classes in Python

Chad Netzer cnetzer at mail.arc.nasa.gov
Fri Apr 18 14:37:13 EDT 2003


On Fri, 2003-04-18 at 08:32, 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.

You were assigning to created instances of class c, not the class
itself.  By assigning to the class object (the object that, when called,
creates instaces a and b), you can create new class attributes that ARE
shared by all instances.  (Note that you can also define the class with
these instances)

$ python
Python 2.2.2 (#1, Mar 21 2003, 23:01:54)

>>> class c:
...     pass
...
>>> a = c()   # These are instances of class c
>>> b = c()
>>> dir(a)
['__doc__', '__module__']
>>> c.foo = 4
>>> dir(a)
['__doc__', '__module__', 'foo']
>>> a.foo
4
>>> b.foo
4

-- 

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)






More information about the Python-list mailing list