use object method without initializing object

Robert Bossy Robert.Bossy at jouy.inra.fr
Tue Apr 15 11:43:25 EDT 2008


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()

RB



More information about the Python-list mailing list