Trying to understand Python objects

Bruno Desthuilliers onurb at xiludom.gro
Wed Nov 22 06:54:22 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?

Apart from a few special cases (mainly builtin types or new-style
classes using slots IIRC), yes.

Now wether this is a good idea is another question. As far as I'm
concerned, I do use this feature, but only for special cases, and almost
only in metaclasses or other special 2-stages init.

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

Nope. The canonical idiom is to use the initializer:

class Point(object):
  def __init__(self, attr1, attr2):
    self.attr1 = attr1
    self.attr2 = attr2
    self.attr3 = 42


> 3) What is with the __underscores__ ??

"magic" methods or attributes. The initializer ('__init__') is one of
them, which is called at instance creation time. Most of the magic
__methods__ are used to implement or override operators. You'll find the
relevant documentation around here:
http://docs.python.org/ref/specialnames.html


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

A class statement is not a function definition statement. Here, you ask
for a class Whatever inheriting from class params. Cf the above point
about the __init__ method for passing args at instanciation.

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

FWIW, Python's classes actually are callable objects (just like
functions are callable objects). To instanciate a class, you just call
the class, no 'new' keyword needed.

> To me, that
> makes more sense.

<?php

class Obj {
  // pass
}

$obj = new Obj();
$obj->name = "toto";
echo $obj->name;

?>

Just like Python (and Javascript FWIW), PHP objects are mostly hashtable
in disguise. But - having some experience with both PHP and Python (and
some other OOPLs), I can tell you that Python's object model is far
superior to PHP's one.

The only "gotcha" here wrt/ most other object models is that attributes
defined in the class statement body (ie, outside methods) are attached
to the class object itself (and then shared by all instances of the
class), not to instances themselves. Instance attributes initialisation
is usually done in the __init__(self, ...) method.

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list