473,513 Members | 2,368 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

What is class method?

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
13 2713
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
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
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
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
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
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
6785
by: Ravi Tallury | last post by:
Hi We are having issues with our application, certain portions of it stop responding while the rest of the application is fine. I am attaching the Java Core dump. If someone can let me know what...
54
6502
by: Brandon J. Van Every | last post by:
I'm realizing I didn't frame my question well. What's ***TOTALLY COMPELLING*** about Ruby over Python? What makes you jump up in your chair and scream "Wow! Ruby has *that*? That is SO...
4
7066
by: Ruud de Jong | last post by:
The question I have is: how safe / future proof / portable is the use of the __subclasses__ method that exists for new-style classes? Background: I thought I had found an easy-to-understand...
31
2478
by: N.Davis | last post by:
I am very new to Python, but have done plenty of development in C++ and Java. One thing I find weird about python is the idea of a module. Why is this needed when there are already the ideas of...
1
10403
by: Mitan | last post by:
Hello, I'm a beginner with what appears to be a simple question for which I haven't been able to get an answer. Can someone explain what "implementation code" is in relation to VB.NET? I want to be...
18
1952
by: cj | last post by:
members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. I'm under the impression before you can use a class you have to make an...
4
3188
by: N.RATNAKAR | last post by:
hai, what is abstract class and abstract method
1
1608
by: truedecembr | last post by:
Hi everyone, I am brand new to Java and not really even sure what I'm doing... I'm supposed to be writing a Timer class that is part of a stop watch application, and it seems to me that the program...
8
1517
by: Viktor | last post by:
Can somebody give me an explanation what happened here (or point me to some docs)? Code: HMMM = None def w(fn): print 'fn:', id(fn) HMMM = fn
0
7175
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7391
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7120
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5697
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5100
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4754
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3235
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1609
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
466
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.