difference between class methods and instance methods

Steven Bethard steven.bethard at gmail.com
Thu Feb 17 11:50:29 EST 2005


John wrote:
> Steven Bethard wrote:
>> John M. Gabriele wrote:
>> class C(object):
>>     @classmethod
>>     def f(cls, *args):
>>         # do stuff
> 
> Sorry -- I'm not as far along as you suspect. :) I've
> never yet seen this "@classmethod" syntax. I'm supposing that
> it's part of this so-called "new-style" class syntax.

This is syntactic sugar in Python 2.4 for:

class C(object):
     def f(cls, *args):
         # do stuff
     f = classmethod(f)

So if you'd like to check the docs, look in the builtins for classmethod 
(and staticmethod):

http://docs.python.org/lib/built-in-funcs.html


>  From your reply, I gather that, unless I'm using this special
> syntax (@classmethod or @staticmethod), all my def's are supposed
> to take 'self' as their first arg.

Yup.  You're of course welcome to name it whatever you like, but the 
methods defined in your class (when not wrapped with classmethod, 
staticmethod, etc.) will all be called with an instance of the class as 
their first argument.  So you need to make sure 'self' or something like 
it is the first parameter to the function.

> So then, are all def's -- that take 'self' as their first --
> argument -- in a class statement, instance methods?

Basically, yes.  (Again, assuming they're not wrapped with anything.)

>> Consider the difference between str.join and ''.join:
>>
>> py> str.join
>> <method 'join' of 'str' objects>
>  >
> 
>> py> ', '.join
>> <built-in method join of str object at 0x01233620>
>  >
> 
> Hmm... weird.

Ok, the point here is that str.join and ', '.join are not the same 
object.  The reason is that, when the ', ' instance of str is created, 
new "bound method" objects are created for each of the instance methods 
in str.  These "bound methods" all know that the first argument to their 
functions is ', '.

>> py> ', '.join(['a', 'b', 'c'])
>> 'a, b, c'
> 
> Check.
> 
>> py> str.join(', ', ['a', 'b', 'c'])
>> 'a, b, c'
> 
[snip]
> What's happening here?

str.join is the "unbound method" of the str object.  So just like you 
have to declare 'self' as the first argument of all your instance 
methods, the writer of the str object methods also declared 'self' as 
the first argumetn to str.join.  So str.join looks something like:

class str(object):
     ...
     def join(self, sequence):
         ...

So when you access it like str.join(...) you should be passing it an 
instance and a sequence.  On the other hand, the "bound method" created 
for ', ' has already bound the instance, so it no longer expects the 
'self' argument to be passed in.

HTH,

STeVe



More information about the Python-list mailing list