use object method without initializing object

colas.francis at gmail.com colas.francis at gmail.com
Tue Apr 15 12:25:08 EDT 2008


On 15 avr, 17:43, Robert Bossy <Robert.Bo... at jouy.inra.fr> wrote:
> Reckoner wrote:
> > would it be possible to use one of an object's methods without
> > initializing the object?
>
> > In other words, if I have:
>
> > class Test:
> >   def __init__(self):
> >       print 'init'
> >   def foo(self):
> >       print 'foo'
>
> > and I want to use the foo function without hitting the
> > initialize constructor function.
>
> > Is this possible?
>
> Hi,
>
> Yes. It is possible and it is called "class method". That is to say, it
> is a method bound to the class, and not to the class instances.
> In pragmatic terms, class methods have three differences from instance
> methods:
>    1) You have to declare a classmethod as a classmethod with the
> classmethod() function, or the @classmethod decorator.
>    2) The first argument is not the instance but the class: to mark this
> clearly, it is usually named cls, instead of self.
>    3) Classmethods are called with class objects, which looks like this:
> ClassName.class_method_name(...).
>
> In your example, this becomes:
>
> class Test(object):
>     def __init__(self):
>         print 'init'
>     @classmethod
>     def foo(cls):
>         print 'foo'
>
> Now call foo without instantiating a Test:
> Test.foo()

To be complete, you can also define a static method that will not even
be passed the class as argument:

In [217]: class Test(object):
   .....:     def __init__(self):
   .....:         print 'init'
   .....:     @staticmethod
   .....:     def foo():
   .....:         print 'foo'
   .....:

In [218]: Test.foo()
foo




More information about the Python-list mailing list