PEP 8 example of 'Function and method arguments'

Steven Bethard steven.bethard at gmail.com
Mon Mar 13 11:48:51 EST 2006


Martin P. Hellwig wrote:
> While I was reading PEP 8 I came across this part:
> 
> """
> Function and method arguments
>    Always use 'self' for the first argument to instance methods.
>    Always use 'cls' for the first argument to class methods.
> """
> 
> Now I'm rather new to programming and unfamiliar to some basic concepts 
> of OOP. However I wrote most of my classes in the new style way and by 
> this I have always used 'self' for the first argument of an Instance 
> method, but now I'm unsure what actually the difference is between an 
> instance and a class method is and when to use it in which case.
> 
> Could somebody please enlighten me (a rtfm/wrong newsgroup is just as 
> welcome of course), preferably in a short code example?

You're probably doing fine.

     class C(object):

         # instance method
         def foo(self):
             ...

         # class method
         @classmethod
         def bar(cls):
             ...

It's probably pretty unlikely that you've declared any class methods, 
but if you have, you should be able to identify them by the call to 
``classmethod``.  If you don't see any of those, you're fine.

A class method is just a method that can be called like:

     Class.method()

instead of having to be called like:

     instance.method()

For 99% of the methods you write, I'd expect them to be instance methods.

STeVe



More information about the Python-list mailing list