[Tutor] calling a method directly

Alan Gauld alan.gauld at btinternet.com
Tue Apr 21 10:03:58 CEST 2015


On 21/04/15 05:19, Jim Mooney wrote:
> Is there any difference between these two since they give the same result,
> and when is the second preferred?
>
>>>> x = 'ABE'
>>>> x.lower()
> 'abe'
>>>> str.lower(x)
> 'abe'
>

They are essentially the same method being accessed in two
different ways. The first via the instance,
the second via the class.

It's a  bit like when you call a superclass method in OOP:
 >>> class C:
...   def f(s): print 'in C'
...
 >>> class D(C):
...   def f(s):
...     C.f(s)
...     print 'and D'
...   def g(s): print 'only D'
...

In the first line of D.f() you invoke C's foo method
by referring to C and passing the local self as the object.

You can do it in top level code too:

 >>> d = D()
 >>> d.f()
in C
and D
 >>> C.f(d)
in C
 >>>
 >>> d.g()
only D
 >>> D.g(d)
only D

There are very few cases where the class version is preferred,
you nearly always use the instance technique.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list