By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,672 Members | 1,644 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,672 IT Pros & Developers. It's quick & easy.

What is class method?

P: n/a
Hi,
I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it?
--
class M:
def method(cls, x):
pass

method = classmethod(method)
--
Thank you for your time.
Aug 24 '08 #1
Share this Question
Share on Google+
13 Replies


P: n/a
On Aug 24, 6:32*pm, Hussein B <hubaghd...@gmail.comwrote:
Hi,
I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it?
--
class M:
*def method(cls, x):
* * pass

*method = classmethod(method)
--
Thank you for your time.
Firstly, don't use method = classmethod(method). Decorators are far
better. The following code has the same effect:

class M:
@classmethod
def method(cls, x):
pass

Far more readable, right?

Class methods are useful if you've got lots of inheritance happening.
The first argument passed in is the class calling the method. Handy
for a mix-in: it can add methods affecting the actual class it's mixed
into, rather than messing with the mix-in itself.
Aug 24 '08 #2

P: n/a
Hussein B <hu********@gmail.comwrites:
Hi,
I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it?
--
class M:
def method(cls, x):
pass

method = classmethod(method)
Use it when your method needs to know what class it is called from.
This makes sense in the context of subclassing:

class M(object):
@classmethod
def method(cls, x):
print cls, x

class N(M):
pass
>>M.method(1)
<class '__main__.M'1
>>N.method(1)
<class '__main__.N'1
Aug 24 '08 #3

P: n/a
On Aug 24, 3:35*am, MeTheGameMakingGuy <gopsychona...@gmail.com>
wrote:
On Aug 24, 6:32*pm, Hussein B <hubaghd...@gmail.comwrote:
Hi,
I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it?
--
class M:
*def method(cls, x):
* * pass
*method = classmethod(method)
--
Thank you for your time.

Firstly, don't use method = classmethod(method). Decorators are far
better. The following code has the same effect:

class M:
*@classmethod
*def method(cls, x):
* pass

Far more readable, right?

Class methods are useful if you've got lots of inheritance happening.
The first argument passed in is the class calling the method. Handy
for a mix-in: it can add methods affecting the actual class it's mixed
into, rather than messing with the mix-in itself.
It is similar to:

class M: #not correct as shown
def newmaker( self, x ):
newinst= self.__class__( arg1, arg2, x )
return newinst

m1= M()
m2= m1.newmaker( 'abc' )

except you don't need the first instance to do it with. Notice you
get a new instance of whatever class m1 is an instance of, rather than
necessarily M.

class N( M ):
pass

m1= N()
m2= m1.newmaker( 'abc' )

m2 is of class N now too.
Aug 24 '08 #4

P: n/a
Le Sunday 24 August 2008 10:32:34 Hussein B, vous avez écrit*:
Hi,
I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it?
--
class M:
def method(cls, x):
pass

method = classmethod(method)
As it has been said, it adds polymorphic behavior to static method concept by
the mean of a reference to the real class that called it.
>>>[159]: class A(object) :
.....: @classmethod
.....: def factory(cls, *args) : return cls(*args)
.....:
.....:
>>>[160]: class B(A) :
.....: def __init__(self, a, b) :
.....: print a, b
.....:
.....:
>>>[161]: A.factory()
...[161]: <__main__.A object at 0x2b88d0e33710>
>>>[162]: B.factory(1, 2)
1 2
...[162]: <__main__.B object at 0x2b88d0e33bd0>

It is a common advice that staticmethod should not exist in python, as theydo
nothing compared to module level functions, and we should always use
classmethods in place of them.
--
Thank you for your time.
--
http://mail.python.org/mailman/listinfo/python-list


--
_____________

Maric Michaud
Aug 24 '08 #5

P: n/a
On Sun, Aug 24, 2008 at 4:32 AM, Hussein B <hu********@gmail.comwrote:
I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it?
"Class Methods" are related to the meta-class concept introduced since
the first beginning of OOP but not known enough so far.
If you are capable to reason (to model) using that concept, the you
will need "classmethod" decorator in Python.

"Static Methods" are global operations but are declared in the
name-space context of a class; so, they are not strictly methods.

In Python everything is an object, but functions declared in the
module scope not receive the instance of the module, so they are not
module methods, they are not methods, they are global functions that
are in the name-space context of the module in this case.

Methods always receive the instance as a special argument (usually
declared as self in Python). Classes (theoretically speaking) are also
objects (dual behavior).

Let's be explicit:

#<code>
class Test(object):
def NormalMethod(self):
print 'Normal:', self

@staticmethod
def StaticMethod(self=None):
print 'Static:', self

@classmethod
def ClassMethod(self):
print 'Class:', self

test = Test()
test.NormalMethod()
test.StaticMethod()
test.ClassMethod() # the instance "test" is coerced to it's class to
call the method.
#</code>

Regards
Aug 24 '08 #6

P: n/a
On Sun, 24 Aug 2008 11:09:46 +0200, Hrvoje Niksic wrote:
Hussein B <hu********@gmail.comwrites:
>Hi,
I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it? --
class M:
def method(cls, x):
pass

method = classmethod(method)

Use it when your method needs to know what class it is called from.

Ordinary methods know what class they are called from, because instances
know what class they belong to:

def method(self, *args):
print self.__class__

You use class methods when you DON'T need or want to know what instance
it is being called from, but you DO need to know what class it is called
from:

@classmethod
def cmethod(cls, *args):
print cls
Why is this useful? Consider the dict method "fromkeys". You can call it
from any dictionary, but it doesn't care which dict you call it from,
only that it is being called from a dict:
>>{}.fromkeys([1, 2, 3])
{1: None, 2: None, 3: None}
>>{'monkey': 42}.fromkeys([1, 2, 3])
{1: None, 2: None, 3: None}
Any method that behaves like dict.fromkeys() is an excellent candidate
for classmethod.


--
Steven
Aug 25 '08 #7

P: n/a
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com.auwrites:
On Sun, 24 Aug 2008 11:09:46 +0200, Hrvoje Niksic wrote:
>Use [classmethod] when your method needs to know what class it is
called from.

Ordinary methods know what class they are called from
I guess I should have added "and no more". :-)
Why is this useful? Consider the dict method "fromkeys". You can
call it from any dictionary, but it doesn't care which dict you call
it from, only that it is being called from a dict:
That's also a good example of the difference between classmethod and
staticmethod, since fromkeys is smart enough to use the type
information.
>>class X(dict):
.... pass
....
>>x = X.fromkeys({1: 2})
type(x)
<class '__main__.X' # not <type 'dict'>

If 'fromkeys' were a staticmethod, it would have to be hardcoded to
always create dicts.
Aug 25 '08 #8

P: n/a
MeTheGameMakingGuy a écrit :
On Aug 24, 6:32 pm, Hussein B <hubaghd...@gmail.comwrote:
>Hi,
I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it?
--
class M:
def method(cls, x):
pass

method = classmethod(method)
--
Thank you for your time.

Firstly, don't use method = classmethod(method). Decorators are far
better. The following code has the same effect:

class M:
@classmethod
def method(cls, x):
pass

Far more readable, right?
Yes, but will only work with Python >= 2.4. There are cases where you
want to keep compatibility with Python 2.3...
Class methods are useful if you've got lots of inheritance happening.
The first argument passed in is the class calling the method. Handy
for a mix-in: it can add methods affecting the actual class it's mixed
into, rather than messing with the mix-in itself.
I'm not sure I get your point here.

As far as I'm concerned, classmethods are useful anywhere you need to
work on the class object itself.
Aug 26 '08 #9

P: n/a
Maric Michaud a écrit :
(snip)
>
It is a common advice that staticmethod should not exist in python, as they do
nothing compared to module level functions,
They "do" nothing more, but are accessible thru a class object instead
of being accessible thru a module object. It sometimes happens to be
useful (for a very very low value of 'sometimes' as far as I'm
concerned, but still...)

Aug 26 '08 #10

P: n/a
On Tue, Aug 26, 2008 at 4:10 PM, Bruno Desthuilliers
<bd*****************@free.quelquepart.frwrote:
In Python, there's *no* relationship between classmethods and metaclasses.
In OOP the concept of meta-class has everything to do with class
methods, regardless if is in Python, SmallTalk or CLOSS. "classmethod"
decorator it's just a syntax sugar structure to define them. There is
no difference (conceptually) on "method1" and "method2":
<sample>
class MetaXClass(type):
def Method1(self): pass
class Xclass(object):
__metaclass__ = MetaXClass
@classmethod
def Method2(self): pass
</sample>
You can drop the 'global' - there's nothing like a real global scope in
Python.

Yes, they are. Functions defined at module level or using staticmethod
decorator don't receive the instance as argument, they are globa,
You can study in Python:
* global keyword
* globals function
Nope. Functions wrapped by a method object receive the instance as *first*
(not 'special') argument. In Python, a method is only a wrapper object
around the function, the class and the instance. This wrapper is built by
the function object's __get__ method (descriptor protocol) each time the
attribute is looked up.
Seriously, I'm a programmer, not a intermediate code engineer. I know
very well how python work in its inner, but this forum is to talk
about Python programming.
Nevertheless, in some level is always call the original defined
function, that YES, it receives the self as an argument.
Why "theoretically speaking" ?
Why not?
>>>isinstance(Foo, object)
True
That's only means that python is nice because fulfills very well the
best OOP theory.
<ot>
pep08 : method names should be all_lower
</ot>
Not for me. I use to be consistent in being pythonic, but there are
some few exceptions.
<ot>
The convention for classmethod is to name the first function argument 'cls'.
</ot>
I just wanted the guy who made the question, don't see other
differences but classmethod decorator.
Sorry!
Nope. There's nothing like "coercion" in Python.
http://docs.python.org/ref/coercion-rules.html
If you really intend to go into low-level explanations of Python's object

I NEVER pretended to do that. Programming I like is high level,
because of that Python is right now my preferred language,
nevertheless I know every thing I'm interested in inner Python.

My best regards
Aug 26 '08 #11

P: n/a
On Aug 24, 5:32*am, Hussein B <hubaghd...@gmail.comwrote:
Hi,
I'm familiar with static method concept, but what is the class method?
how it does differ from static method? when to use it?
I use them when I need alternative constructors for a class.

class Angle(object):

def __init__(self, degrees):
self.degrees = degrees

@classmethod
def from_radians(cls, radians):
return cls(radians / pi * 180.0)

This lets me construct a new angle with either Angle(45) or
Angle.from_radians(pi/4).

The example shows what is special about classmethods. The first
argument is a class, not an instance.
Raymond
Aug 26 '08 #12

P: n/a
Medardo Rodriguez (Merchise Group) wrote:
On Tue, Aug 26, 2008 at 4:10 PM, Bruno Desthuilliers
<bd*****************@free.quelquepart.frwrote:
>In Python, there's *no* relationship between classmethods and metaclasses.

In OOP the concept of meta-class has everything to do with class
methods, regardless if is in Python, SmallTalk or CLOSS. "classmethod"
decorator it's just a syntax sugar structure to define them. There is
no difference (conceptually) on "method1" and "method2":
<sample>
class MetaXClass(type):
def Method1(self): pass
class Xclass(object):
__metaclass__ = MetaXClass
@classmethod
def Method2(self): pass
</sample>
Not quite:
>>class MetaXClass(type):
.... def method1(self): pass
....
>>class XClass(object):
.... __metaclass__ = MetaXClass
.... @classmethod
.... def method2(self): pass
....
>>xc = XClass()
xc.method1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'XClass' object has no attribute 'method1'
>>xc.method2
<bound method MetaXClass.method2 of <class '__main__.XClass'>>
>>>
-Matt
Aug 26 '08 #13

P: n/a
Medardo Rodriguez (Merchise Group) a écrit :
On Tue, Aug 26, 2008 at 4:10 PM, Bruno Desthuilliers
<bd*****************@free.quelquepart.frwrote:
>In Python, there's *no* relationship between classmethods and metaclasses.

In OOP the concept of meta-class has everything to do with class
methods, regardless if is in Python, SmallTalk or CLOSS.
Ok, I guess we're not going to agree here, since you take for granted
that there's such a thing as a universal, language-independant
definition of OOP concepts, and I don't (except for the two very basic
concepts : 1/ an object is defined by an identity, a state and a
behaviour, 2/ objects interact by sending messages to each others).
"classmethod"
decorator it's just a syntax sugar structure to define them. There is
no difference (conceptually) on "method1" and "method2":
<sample>
class MetaXClass(type):
def Method1(self): pass
class Xclass(object):
__metaclass__ = MetaXClass
@classmethod
def Method2(self): pass
</sample>
There's two obvious differences : Method1 is an instance method of class
MetaXClass, and can only be called on instances of MetaXClass, while
Method2 is a class method of class Xclass and can be called on either
Xclass or instances of Xclass.

>You can drop the 'global' - there's nothing like a real global scope in
Python.


Yes, they are. Functions defined at module level or using staticmethod
decorator don't receive the instance as argument,
Nested functions don't receive "the" instance as argument neither...
they are globa,
staticmethods are not, even from a Python-specific POV.
You can study in Python:
* global keyword
* globals function
I don't think I need to study them, thanks.

But I must admit that since I disagree with you on the basis of "generic
CS concept vs Python specific concept", I shouldn't have mentionned this
- from a Python specific POV, functions defined at the top-level of a
module are indeed "globals" (just like any name bound at the module
level). OTHO, you too are now relying on the python-specific definition
of "global" here.
>Nope. Functions wrapped by a method object receive the instance as *first*
(not 'special') argument. In Python, a method is only a wrapper object
around the function, the class and the instance. This wrapper is built by
the function object's __get__ method (descriptor protocol) each time the
attribute is looked up.

Seriously, I'm a programmer, not a intermediate code engineer. I know
very well how python work in its inner, but this forum is to talk
about Python programming.
Indeed.
Nevertheless, in some level is always call the original defined
function, that YES, it receives the self as an argument.
Sorry, I don't understand the above sentence (seriously - no nitpicking
here).
>Why "theoretically speaking" ?

Why not?
Hmmm.... Because in Python, classes *are* objects, and not only from a
theoretical POV ?-)
>>>>isinstance(Foo, object)
True

That's only means that python is nice because fulfills very well the
best OOP theory.
Which one ? Java's OOP theory ? Smalltalk's OOP theory ? CLOS OOP
theory? Javascript's OOP theory ? Io's OOP theory ? Eiffel's OOP theory?

As far as I'm concerned, there are as many "OOP theories" as they are
"OOP languages".
><ot>
pep08 : method names should be all_lower
</ot>

Not for me. I use to be consistent in being pythonic, but there are
some few exceptions.
<ot>
Coming from the Windows world ?
</ot>
><ot>
The convention for classmethod is to name the first function argument 'cls'.
</ot>

I just wanted the guy who made the question, don't see other
differences but classmethod decorator.
Sorry!
>Nope. There's nothing like "coercion" in Python.

http://docs.python.org/ref/coercion-rules.html
Ok, you got me on this one. What I meant was that there was nothing
like typecasting. *And* the way the class is passed to classmethods
called on an instance has nothing to do with coercion anyway (at least
for commonly accepted definitions of 'coercion').
>If you really intend to go into low-level explanations of Python's object


I NEVER pretended to do that.
Sorry for this last paragraph anyway. I often tend to get too harsh, and
regret it later. Sincerely.
Best regards, and thanks for not being as ill-tempered as I tend to.
Aug 27 '08 #14

This discussion thread is closed

Replies have been disabled for this discussion.