[Tutor] I can't understand where python class methods come from

Alan Gauld alan.gauld at btinternet.com
Mon Feb 24 01:26:38 CET 2014


On 23/02/14 21:59, 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

Ben has already addressed much of your confusion.
I'd just add that if you look at C++ operator overloading it is very 
similar to Python's except that the C++ operators are more literally 
like their usage.

Thus in C++ to overload the plus sign you write something like
(I'm a bit rusty so the detail might be wrong...):

class C{
public:
    C(int n){
       this.data = n;
    };

    C* operator+(C c){
       return new C(c.data + this.data);
    };
};

myC1 = C(42);
myC2 = C(66);

void main(){
    cout << myC1 + myC2;
}

In Python that is very like

class C:
   def __init__(self,n):
      self.data = n
   def __add__(self, aCobj):
      return self.data + aCobj.data

c1 = C(42)
c2 = C(66)
print (c1 + c2)

In both languages a bit of magic happens to turn __add__ or
operator+ into the infix + operator.

> find where each class was defined and what methods were defined inside
> them.

Are you sure? That has always been one of the big challenges in OOP, 
finding where operations are defined. Especially in deep inheritance 
hierarchies. That's where explorer type tools can help.
Python provides such help via the help() function.
Often it will show you where a published method is defined.

> 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.

They are always defined but the location and timing can be different. 
That's part of the dynamic nature of Python.

[ Just be thankful it's not lisp which allows you to change all aspects 
of the objects, including the method search algorithm, at runtime...]

> Let's have a look at the pygeocoder library located here:
> http://code.xster.net/pygeocoder/src/8888c863f907f8a706545fa9b27959595f45f8c5/pygeolib.py?at=default

There are many "smart" third party modules.
Sometimes for good reasons, sometimes because the author found
a clever solution and wanted to use it. Python is a broad church
and while the standard library is fairly conventional for the
most part third party libraries are the sole responsibility
of their maintainers and may not be so readily understood.

But then again many C libraries are obscure in the extreme,
that's not the language's fault, it's just  open and flexible.
You have the choice to use it without fully understanding,
spend time to understand, find an alternative or write your
own...

hth
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list