Classes in Python

Roy Smith roy at panix.com
Fri Apr 18 18:41:20 CEST 2003


Bill Martin <wcmartin at vnet.net> wrote:
> I'm wondering about the value of allowing a class definition like this:
> 
>              class C:
>                pass

The most common use I can think for an empty class like that is for 
defining exceptions.

> 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.

Of course :-)

When you said a = c(), you generated an instance of c.  Likewise, b = 
c() generated a second instance.  These both inherit everything that the 
base class has (which in this case, is nothing).

Next, you said, a.x1 = 1.2, creating an attribute x1 in instance a.  
This doesn't create an attribute x1 in the entire class, just in the 
particular instance a.  So, when you tried to access b.x1, you got an 
error.

You can see what attributes any object has with the dir() function.  It 
might be instructive to try playing around with code like this and watch 
what happens:

class c:
   pass

dir(c)

a = c()
dir(a)
a.x = 1
dir(a)
dir(c)

c.y = 2
dir(c)
b = c()
dir(a)
dir(b)
dir(c)

Extra credit for deranged minds: figure out a way to make:

a = c()
b = c()

try:
   print b.x
except AttributeError:
   print "wugga wugga"

a.x = "foo"

try:
   print b.x
except AttributeError:
   print "wugga wugga"

print "wugga wugga" and then print "foo".  Here's an example to prove it 
works (on Python 2.2):

bash-2.05a$ ./deranged.py 
wugga wugga
foo




More information about the Python-list mailing list