PEP 8 example of 'Function and method arguments'

bruno at modulix onurb at xiludom.gro
Mon Mar 13 13:42:09 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.

As you noticed, an instance method gets an instance as the first
parameter (usually named 'self'), and does something with this instance.
A class method doesn't takes the instance as first parameter, but the
class itself, and does something with the class (NB: in Python, classes
are objects too...).

Note that, as well as class methods, there are class variables (see
below for an example).

> Could somebody please enlighten me (a rtfm/wrong newsgroup is just as
> welcome of course),

No problem, you're at the right place.

> preferably in a short code example?

A stupid exemple that won't teach you much about the usefulness of class
methods :

class Foo(object):
  # a class variable:
  _number_of_foos = 0

  # a class method
  @classmethod
  def increase_foo_counter(cls):
     cls._number_of_foos +=1

  # another class method
  @classmethod
  def decrease_foo_counter(cls):
     cls._number_of_foos -=1

  # and a third one
  @classmethod
  def get_foos_count(cls):
    return cls._number_of_foos

  # instance methods
  def __init__(self):
    self.increase_foo_counter()
    print "now we have %d foos" % self.get_foos_count()

  def __del__(self):
    self.decrease_foo_counter()
    print "now we have %d foos" % self.get_foos_count()

foos = [Foo() for i in range(10)]
print "how many foos ? %d " % Foo.get_foos_count()
del foos


Note that a class method can be called on the class itself or on any of
it's instances - it'll still get the class as first param.


FWIW, you won't probably need class methods before you get much more
familiar with OO. Not that they are an advanced topic by themselves, but
their usefulness appears mostly in heavyly OO designs.

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list