[Tutor] Methods and classes

Alan Gauld alan.gauld at btinternet.com
Fri Sep 15 01:38:47 CEST 2006


"Kent Johnson" <kent37 at tds.net> wrote
> You have to distinguish between a method (a function that is part of 
> a
> class definition) and a standalone function (not part of any class).
> Python allows both. Standalone functions don't have a 'self' 
> parameter;
> class methods always do (you can give it a different name but if you
> omit it you will get a runtime error when you call the method).

Just to be picky, instance methods need a self parameter.
class methods (ie methods that belong to the class as a whole
rather than the individual instances(objects)) do not need a self
parameter.

>>> class C:
...  def s_m(x): print x
...  s_m = staticmethod(s_m)   # make it a static or class method
...  def __init__(self,y): self.y = y
...  def i_m(self,x): print x, self.y
...
>>> c = C(27)
>>> C.s_m(42)  # call via class
42
>>> c.s_m(42) # call via instance
42
>>> c.i_m(42)
42 27
>>>

And just to be even more picky Python actually distinguishes
between static methods (as above) and what it specifically
calls class methods, whereby the latter have an attribute similar
to self, but instead of holding the instance it holds a reference
to the original class object! (most OOP languages do not have
such fine grained distinctions on class methods)

So to summarise there are 4 types of function/method definition:
1) Ordinary functions - can have any parameters, including none
2) static methods - ordinary functions bound to a class object
3) class methods - static methods with a class reference as first 
parameter
4) instance methods - a function bound to an instance of the class
   and with an instance reference as the first parameter.

2,3 and 4 must all be defined inside a class definition.

[ And if you use decorators you can add to that list, but I won't go 
there! :-) ]

Finally the double underscore that you refer to is a Python
convention (but strongly adhered to) which indicates a special
function used by Python internally and not normally called by
the programmer..

__init__ is the initialisation function called automatically when
an instance is created. Because it is specifc to the instance
it has a self at the front. It can also take other values which will
initialise internal values of the instance, like my self.y above.

Others allow you to define how standard operators will work
for your own classes, thus __add__, __mul__, __cmp__ etc

If you define an __add__() method in your class, you can
then add two instances using the + sign:

class M:
   def __add__(self,another):
       return 42

m = M()
n = M()
print m+n   # python calls M.__add__(m,n) under the covers



HTH,
-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list