Trying to understand Python objects

George Sakkis george.sakkis at gmail.com
Tue Nov 21 19:42:05 EST 2006


walterbyrd wrote:

> Reading "Think Like a Computer Scientist" I am not sure I understand
> the way it describes the way objects work with Python.
>
> 1) Can attributes can added just anywhere? I create an object called
> point, then I can add attributes any time, and at any place in the
> program?

For user-defined (i.e. not builtin) classes, yes. There are ways to
prevent this (or at least it make it harder), but they're usually not
worth it unless you have pretty good reasons to do it. And just in case
you're wondering, "that's how php/c++/java/whatever does it" doesn't
count as a pretty good reason.

> 2) Are classes typically created like this:
>
> class Point:
>   pass
>
> Then attributes are added at some other time?

Yes, you can do it. No, it is not typical. The typical is to initialize
all class attributes in the class body, and all instance attributes in
__init__:

class Point(object):            # prefer new-style classes in new code
    num_instances = 0           # a class attribute

    def __init__(self, x, y):
        self.x, self.y = x,y     # instance attributes

There are cases where this is not possible or desirable; Python doesn't
get in your way in these cases, but they are certainly not typical.

> 3) What is with the __underscores__ ??

They're special attributes, usually methods that perform "operator
overloading". If the term doesn't mean anything to you, think of it as
a method that is called implicitly by a specific operator. E.g. instead
of having a normal method add() and then call it as a.add(b), you can
define the special method __add__ and have it called when you write a +
b. There are several details I left out but that's the gist of it.

> 4) Are parameters passed to an class definition?
>
> class Whatever(params):
>    pass

No, these are not parameters, they are the base (aka "super") clasess
of Whatever.

> I sort-of understand the way objects work with PHP. With PHP, the
> classes are defined in one place - sort of like a function. To me, that
> makes more sense.

It makes sense in Python too, see point (2). The difference is that for
the few cases that it either doesn't make sense or it's less convenient
or desirable, Python doesn't get in your way.

HTH,
George




More information about the Python-list mailing list