On 02/23/2014 10:59 PM, voger wrote:
I have a really hard time understanding where methods are defined in python
classes. My first contact with programming was with C++ and Java
and even if I was messing with them in a very amateurish level, I could find
where each class was defined and what methods were defined inside them.
Everything was clear and comprehensive. With python everything looks like magic.
Methods and properties appearing out of nowhere and somehow easing the task at
hand. I am not complaining for their existence but I really can't understand how
and what is defined so I can use it.
In general, python classes look like:
class Point:
def __init__ (self, x, y):
self.x = x
self.y = y
self.d = x + y # square distance
def move (self, dx, dy):
self.x += dx
self.y == dy
def __str__ (self):
return "{%s %s}" % (self.x, self.y)
(Try using it if needed.)
A valid complaint --which I share-- is that python classes do not obviously show
data attributes. Maybe from other languages you'd rather expect something like:
class Point:
data = x , y, d # data attr (no static typing)
def __init__ (self, x, y):
self.d = x + y # square distance
def move (self, dx, dy):
self.x += dx
self.y == dy
def __str__ (self):
return "{%s %s}" % (self.x, self.y)
In python, you have to look inside __init__ (and sometimes also other methods
just to know what are the actual data defining a given class's instances.
Enough ranting and let me give an example of what I mean.
Let's have a look at the pygeocoder library located here:
http://code.xster.net/pygeocoder/src/8888c863f907f8a706545fa9b27959595f45f8c5/pygeolib.py?at=default
This code is very unusual and indeed pretty magic. The big schema is that
instead of computing and setting all data attributes at init time, it only does
it *on demand*. To do so, it intercepts your requests (eg "x = addr.attr") in
the "magic metamethod" called __getattr__. This method is called, as name
suggests, when you request to read one of an object's attributes.
You can even to similar magic with methods (since they are looked up as well),
but it even more rare. Anyway, such metamagic is indeed advanced python
programing and maybe you shouldn't bother with it now.
d
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor