Classes in Python

Steve Holden sholden at holdenweb.com
Fri Apr 18 17:42:16 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
>
> 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
--
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/








More information about the Python-list mailing list