Classes in Python

Andy Jewell andy at wild-flower.co.uk
Fri Apr 18 14:58:06 EDT 2003


On Friday 18 Apr 2003 4:42 pm, Steve Holden wrote:
> "Bill Martin" <wcmartin at vnet.net> 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,
>
> Well, if you think it's dangerous you probably *don't* want to do it, but
> it's the easiest way to set up a data structure with named components - you
> are just taking advantage of the fact that each instance has its own
> namespace. It's a firly standard idiom, though it isn't required.
>
> Now, other object-oriented languages can go to great pains to make sure
> that an instance's attributes can only be accessed in very controlled ways,
> such as using accessor methods (getthis(), setthat(), etc.). Python, on the
> other hand, pays you the compliment of assuming you know what you are
> doing, and "gives you enough rope to shoot yourself in the foot"!
>
> If you choose to abuse that freedom, you end up with a limp. [Please,
> nobody ask "a limp what?"].
>
> regards

In all my days playing with rope, I've never managed to shoot myself with it.  
Hang myself, maybe, but not shoot myself.  :-)

I think, however, that Bill was trying to say that it is dangerous for Python 
not to behave in the manner he expected...

Shuffling off to the gallows pole...

-andyj





More information about the Python-list mailing list