473,769 Members | 6,120 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(met hod)
--
Thank you for your time.
Aug 24 '08 #1
13 2741
On Aug 24, 6:32*pm, Hussein B <hubaghd...@gma il.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(met hod)
--
Thank you for your time.
Firstly, don't use method = classmethod(met hod). 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********@gma il.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(met hod)
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, MeTheGameMaking Guy <gopsychona...@ gmail.com>
wrote:
On Aug 24, 6:32*pm, Hussein B <hubaghd...@gma il.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(met hod)
--
Thank you for your time.

Firstly, don't use method = classmethod(met hod). 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(met hod)
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********@gma il.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 "classmetho d" 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(se lf):
print 'Normal:', self

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

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

test = Test()
test.NormalMeth od()
test.StaticMeth od()
test.ClassMetho d() # 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********@gma il.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(met hod)

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
MeTheGameMaking Guy a écrit :
On Aug 24, 6:32 pm, Hussein B <hubaghd...@gma il.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(met hod)
--
Thank you for your time.

Firstly, don't use method = classmethod(met hod). 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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
6814
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 the issue is. Thanks Ravi
54
6576
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 FRICKIN' COOL!!! ***MAN*** that would save me a buttload of work and make my life sooooo much easier!" As opposed to minor differences of this feature here, that feature there. Variations on style are of no interest to me. I'm coming at this from a...
4
7099
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 application for metaclasses: making classes instantly aware of their subclasses. The context was that I needed a class hierarchy, and I wanted to be able to instantiate subclasses by calling the root class. Which exact subclass would be instantiated...
31
2534
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 class, file, and package? To my mind, although one CAN put many classes in a file, it is better to put one class per file, for readability and maintainability. One can then create packages and libraries, using groups of files, one
1
10419
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 sure I have a good understanding of this before I continue with my studies. Thanks in advance. Semper Fi
18
1982
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 instance of it. So how can a class be threadsafe by itself but an instance of it not be? I guess I don't get what exactly being threadsafe means. Multiple theads can use the same instance of a class?
4
3205
by: N.RATNAKAR | last post by:
hai, what is abstract class and abstract method
1
1622
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 is correct, but when I run the tester, it is obviously not. The goal is to enter a base and a time, and find time % base, then tell how many times it cycled back to zero. I don't know what is wrong with my program, because it appears to me that it...
8
1535
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
10223
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10051
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10000
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9866
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8879
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6675
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3968
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 we have to send another system
2
3571
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.