Trying to understand Python objects
Gabriel Genellina
gagsl-py at yahoo.com.ar
Tue Nov 21 19:28:00 EST 2006
At Tuesday 21/11/2006 20:03, walterbyrd wrote:
>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 "normal" python objects, yes, you can add/delete any attribute,
anytime, anywhere. There are hooks where you can actively deny
attribute creation, or "freeze" the attribute list, but these are
considered advanced usage.
>2) Are classes typically created like this:
>
>class Point:
> pass
>
>Then attributes are added at some other time?
Not "typically"! Although you *can* do that, doesn't mean that you
*must* do things that way.
A 2D point might say:
class Point2D(object):
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
return math.hypot(other.x-self.x, other.y-self.y)
p0 = Point2D(3, 2)
p1 = Point2D(0, 6)
p0.distance(p1) # gives 5
>3) What is with the __underscores__ ??
Names that begin and end in __ are used by Python itself and have
some "magic" attached sometimes. The most common is __init__ (used to
initialize a new instance). __str__ by example, is used to get an
object's textual representation suitable for printing. If you execute
>>> print p0
using the example above, you'll get something like <Point2D instance
at 0x12345678>. Add the following to the Point2D class and you get a nice pair:
def __str__(self):
return '(%f, %f)' % (self.x, self.y)
>4) Are parameters passed to an class definition?
>
>class Whatever(params):
> pass
If you see something like that, "params" are not parameters, but base
classes. The Whatever class inherits all attributes and methods known
to its bases, and may provide its own.
>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.
Usually in Python you also define a class in only one place - you
*can* modify it later, and that's a powerful feature, but certainly
you don't have to!
--
Gabriel Genellina
Softlab SRL
__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
More information about the Python-list
mailing list