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
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor