473,594 Members | 2,713 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

classmethod & staticmethod

hi,

python's staticmethod is the equivalent of java staticmethod right?

with classmethod, I can call the method without the need for creating
an instance right? since the difference between the two is that
classmethod receives the class itself as implicti first argument. From
my understanding classmethod are for dealing with class attributes?

Can somebody teach me the real use of classmethod & staticmethod?

Thanks
james

Jul 24 '07 #1
14 2721
On Tue, 24 Jul 2007 03:19:05 +0000, james_027 wrote:
python's staticmethod is the equivalent of java staticmethod right?
Correct. `staticmethod` is essentially just a function moved into a class
and accessible at the class object and instances of that class.

As Python opposed to Java has functions, `staticmethod` isn't that useful.
with classmethod, I can call the method without the need for creating
an instance right? since the difference between the two is that
classmethod receives the class itself as implicti first argument. From
my understanding classmethod are for dealing with class attributes?
It's possible to access class attributes and, maybe more important, it's
possible to call the class to return an instance. So if you call a
`classmethod` on a subclass an instance of that subclass is returned.
Silly example:

class A(object):
def __init__(self, x, y):
print 'init A'
self.x = x
self.y = y

@classmethod
def from_str(cls, string):
return cls(*map(float, string.split(', ')))
class B(A):
def __init__(self, x, y):
print 'init B'
A.__init__(self , x, y)
def main():
B.from_str('42, 23')

Ciao,
Marc 'BlackJack' Rintsch
Jul 24 '07 #2
james_027 a écrit :
hi,

python's staticmethod is the equivalent of java staticmethod right?
IIRC, yes. A 'staticmethod' is in fact nothing more than a function
attached to a class, and which can be called on the class or an instance
of. Note that since Python supports modules and functions, staticmethods
are of little practical use.
with classmethod, I can call the method without the need for creating
an instance right? since the difference between the two is that
classmethod receives the class itself as implicti first argument.
Yes.
From
my understanding classmethod are for dealing with class attributes?
Not necessarily - you can access class attributes from within an
instance method (but obviously a classmethod cannot access instance
attributes).
Can somebody teach me the real use of classmethod & staticmethod?
The 'real' use is (are) the one(s) you'll find. FWIW, I use
staticmethods for helper functions that don't need access to the class
or instance but are too specific to a class to be of any use as plain
functions. Which is not a very frequent case. Classmethods are more
usefull - mostly as alternate constructors or utility methods for an
alternate constructor, but there are other possible uses (sorry, I have
no concrete example at hand).
Jul 24 '07 #3
hi,
The 'real' use is (are) the one(s) you'll find. FWIW, I use
staticmethods for helper functions that don't need access to the class
or instance but are too specific to a class to be of any use as plain
functions. Which is not a very frequent case. Classmethods are more
usefull - mostly as alternate constructors or utility methods for an
alternate constructor, but there are other possible uses (sorry, I have
no concrete example at hand).
You mean like the example from Marc

Thanks
james

Jul 24 '07 #4
james_027 a écrit :
hi,
>The 'real' use is (are) the one(s) you'll find. FWIW, I use
staticmethod s for helper functions that don't need access to the class
or instance but are too specific to a class to be of any use as plain
functions. Which is not a very frequent case. Classmethods are more
usefull - mostly as alternate constructors or utility methods for an
alternate constructor, but there are other possible uses (sorry, I have
no concrete example at hand).

You mean like the example from Marc
Marc's example is typically an alternate constructor. This is indeed one
of the most obvious use case of classmethod, but what I meant is that
there are others cases where classmethods can help.

Jul 24 '07 #5
On 2007-07-24, Alex Popescu <no************ *****@gmail.com wrote:
Bruno Desthuilliers <br************ ********@wtf.we bsiteburo.oops. comwrote
in news:46******** *************** @news.free.fr:

>>
[snip...]
Not necessarily - you can access class attributes from within an
instance method (but obviously a classmethod cannot access instance
attributes).

What I am doing wrong here then:

class MyClass(object) :
class_list = ['a', 'b']

def instance_method (self):
print "instance_metho d with class list %s" % class_list
There's no implicit self or class for Python identifiers.

The name class_list must be quailified: self.class_list or
MyClass.class_l ist.

--
Neil Cerutti
Jul 24 '07 #6
Neil Cerutti <ho*****@yahoo. comwrote in
news:sl******** ************@FI AD06.norwich.ed u:
On 2007-07-24, Alex Popescu <no************ *****@gmail.com wrote:
>Bruno Desthuilliers <br************ ********@wtf.we bsiteburo.oops. com>
wrote in news:46******** *************** @news.free.fr:

[snip...]
>>
class MyClass(object) :
class_list = ['a', 'b']

def instance_method (self):
print "instance_metho d with class list %s" % class_list

There's no implicit self or class for Python identifiers.

The name class_list must be quailified: self.class_list or
MyClass.class_l ist.
After more investigation I have figured this out by myself, but thanks for
the details.
Now I am wondering if in the above case there is a prefered way:
MyClass.class_l ist or self.__class__. class_list? (IMO the 2nd is more safe
in terms of refactorings).

../alex
--
..w( the_mindstorm )p.

Jul 24 '07 #7
On Tue, 24 Jul 2007 21:35:58 +0000, Alex Popescu wrote:
Neil Cerutti <ho*****@yahoo. comwrote in
news:sl******** ************@FI AD06.norwich.ed u:
>On 2007-07-24, Alex Popescu <no************ *****@gmail.com wrote:
>>Bruno Desthuilliers <br************ ********@wtf.we bsiteburo.oops. com>
wrote in news:46******** *************** @news.free.fr:

[snip...]
>>>
class MyClass(object) :
class_list = ['a', 'b']

def instance_method (self):
print "instance_metho d with class list %s" % class_list

There's no implicit self or class for Python identifiers.

The name class_list must be quailified: self.class_list or
MyClass.class_ list.

After more investigation I have figured this out by myself, but thanks for
the details.
Now I am wondering if in the above case there is a prefered way:
MyClass.class_l ist or self.__class__. class_list? (IMO the 2nd is more safe
in terms of refactorings).
Consider what happens when you sub-class:

class MyClass(object) :
class_list = [1, 2, 3]
def method(self, x):
return sum(MyClass.cla ss_list) + x

class MySubclass(MyCl ass):
class_list = ['a', 'b', 'c'] # over-ride the class attribute

expecting_a_str ing = MySubclass().me thod('x')
Use a direct reference to MyClass.class_l ist when you want a direct
reference to MyClass regardless of which instance or class you are calling
from.

Use self.class_list when you want to use inheritance.

Use self.__class__. class_list when you have an instance method and you
need the class it belongs to.

Use a classmethod and the first argument (by convention called klass
or cls) when you don't care about the instance and just want the class.

--
Steven.

Jul 24 '07 #8
"Steven D'Aprano" <st***@REMOVE.T HIS.cybersource .com.auwrote in
news:pa******** *************** *****@REMOVE.TH IS.cybersource. com.au:
On Tue, 24 Jul 2007 21:35:58 +0000, Alex Popescu wrote:
>Neil Cerutti <ho*****@yahoo. comwrote in
news:sl******* *************@F IAD06.norwich.e du:
>>On 2007-07-24, Alex Popescu <no************ *****@gmail.com wrote:
Bruno Desthuilliers
<br********* ***********@wtf .websiteburo.oo ps.comwrote in
news:46***** *************** ***@news.free.f r:
[snip...]

Use self.class_list when you want to use inheritance.
As a matter of style, how do you figure out that class_list is a class
attribute and not an instance attribute? (I don't remember seeing anything
in the PEP describing the coding style).

tia,
../alex
--
..w( the_mindstorm )p.

Jul 25 '07 #9
On 2007-07-25, Alex Popescu <no************ *****@gmail.com wrote:
As a matter of style, how do you figure out that class_list is
a class attribute and not an instance attribute? (I don't
remember seeing anything in the PEP describing the coding
style).
Check out dir(MyClass) and dir(MyClass()) for some insight, if it
turns out that it matters. Preferably, the user of a class
doesn't have to really think about it much.

--
Neil Cerutti
Jul 25 '07 #10

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

Similar topics

4
5920
by: Michal Vitecek | last post by:
hello everyone, today i've come upon a strange exception, consider the following file test.py: --- beginning of test.py --- class A(object): def method1(parA): print "in A.method1()"
0
1313
by: Karl Chen | last post by:
Hi. Is it possible to make a classmethod out of __getitem__? I.e. I want to do: class C: def __getitem__(p): return 1+p
0
1605
by: Robin Becker | last post by:
A colleague wanted to initialize his class __new__ and tried code resembling this #######################1 class Metaclass (type): def __init__(cls, name, bases, *args, **kwargs): super(Metaclass, cls).__init__(cls, name, bases, *args, **kwargs) print 'cls=',cls, cls.__new cls.__new__ = staticmethod(cls.__new) def __new(self,cls,*args):
1
1970
by: Neil Zanella | last post by:
Hello, Coming from C++ and Java, one of the surprising things about Python is that not only class instances (AKA instance objects) but also classes themselves are objects in Python. This means that variabls such as x and y appearing inside class statements in Python essentially behave like static class variables in other languages. On the other hand a variable is specified as an instance variable as self.x and self.y inside a class in...
3
1964
by: Neil Zanella | last post by:
Hello, In Python, classes are objects. But there is no way to custom print a class object. This would require some syntax such as the one commented out below: With the current "foo = classmethod(foo)" mechanism custom printing for class objects is not possible. #!/usr/bin/python class Foo:
5
17260
by: C Gillespie | last post by:
Hi, Does anyone know of any examples on how (& where) to use staticmethods and classmethods? Thanks Colin
3
2017
by: Giovanni Bajo | last post by:
Hello, what's the magic needed to reuse the base-class implementation of a classmethod? class A(object): @classmethod def foo(cls, a,b): # do something pass
6
1272
by: Laszlo Zsolt Nagy | last post by:
Hello, Is it possible to tell, which instance was used to call the classmethod that is currently running? Background: I have a class called DatabaseConnection and it has a classmethod called process_create_tables. This method should create some database tables defined by a database definition object. The DatabaseConnection has many descendants, for example PostgreSQLConnection. Descendants know how to create tables in a given
10
6991
by: Nicolas Fleury | last post by:
Hi everyone, I was wondering if it would make sense to make staticmethod objects callable, so that the following code would work: class A: @staticmethod def foo(): pass bar = foo() I understand staticmethod objects don't need to implement __call__ for
0
7946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7876
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8372
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
8003
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
8234
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...
1
5739
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3859
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
1478
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1210
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.