On 21Apr2015 09:03, alan.ga...@btinternet.com <alan.ga...@btinternet.com> wrote:
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.

Though only because 'x' is directly a str. Not some other class. In Jim's example we _know_ 'x' is a str. In general one is less sure, and often one hopes not to care!

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.

Worth pointing out that this is almost always the only time you cant to call via the class directly. And that it is actually common in subclass method implementations, particularly __init__, where on must often go:

 class D(C):
   def __init__(self, blah...):
     # initialise the common "C" class related stuff
     C.__init__(self, ...)
     # intialise the specific "D" class related stuff
     ... D-specific-stuff-here ...

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

Indeed. Not least because (a) you don't always know or even care what class an object is and (b) objects themselves can have callable attributes.

Cheers,
Cameron Simpson <c...@zip.com.au>

Applications Programming is for dullards who can't do Systems Programming.
       - David Rose, d...@werple.apana.org.au
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to