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 14 2698
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
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).
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
james_027 a écrit :
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
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.
On 2007-07-24, Alex Popescu <no*****************@gmail.comwrote:
Bruno Desthuilliers <br********************@wtf.websiteburo.oops.comwr ote
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_method 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.
--
Neil Cerutti
Neil Cerutti <ho*****@yahoo.comwrote in
news:sl********************@FIAD06.norwich.edu:
On 2007-07-24, Alex Popescu <no*****************@gmail.comwrote:
>Bruno Desthuilliers <br********************@wtf.websiteburo.oops.com > wrote in news:46***********************@news.free.fr:
[snip...]
>> class MyClass(object): class_list = ['a', 'b']
def instance_method(self): print "instance_method 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_list or self.__class__.class_list? (IMO the 2nd is more safe
in terms of refactorings).
../alex
--
..w( the_mindstorm )p.
On Tue, 24 Jul 2007 21:35:58 +0000, Alex Popescu wrote:
Neil Cerutti <ho*****@yahoo.comwrote in
news:sl********************@FIAD06.norwich.edu:
>On 2007-07-24, Alex Popescu <no*****************@gmail.comwrote:
>>Bruno Desthuilliers <br********************@wtf.websiteburo.oops.com > wrote in news:46***********************@news.free.fr: [snip...]
>>> class MyClass(object): class_list = ['a', 'b']
def instance_method(self): print "instance_method 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_list 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.class_list) + x
class MySubclass(MyClass):
class_list = ['a', 'b', 'c'] # over-ride the class attribute
expecting_a_string = MySubclass().method('x')
Use a direct reference to MyClass.class_list 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.
"Steven D'Aprano" <st***@REMOVE.THIS.cybersource.com.auwrote in
news:pa****************************@REMOVE.THIS.cy bersource.com.au:
On Tue, 24 Jul 2007 21:35:58 +0000, Alex Popescu wrote:
>Neil Cerutti <ho*****@yahoo.comwrote in news:sl********************@FIAD06.norwich.edu:
>>On 2007-07-24, Alex Popescu <no*****************@gmail.comwrote: Bruno Desthuilliers <br********************@wtf.websiteburo.oops.co mwrote in news:46***********************@news.free.fr:
[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.
On 2007-07-25, Alex Popescu <no*****************@gmail.comwrote:
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
Neil Cerutti <ho*****@yahoo.comwrote in news:eRwpi.36813$G23.28496
@newsreading01.news.tds.net:
On 2007-07-25, Alex Popescu <no*****************@gmail.comwrote:
>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.
I must confess that I am a bit confused by this advise, as both are
returning exactly the same thing.
Preferably, the user of a class
doesn't have to really think about it much.
I know that this would be prefered, but in case you are getting 3rd party
code and you modify a class attribute without knowing it is a class
attribute then you may get into trouble (indeed the real problem is with
the designer of the 3rd party code, but still I think it is a valid
concern).
tia,
../alex
--
..w( the_mindstorm )p.
Alex Popescu a écrit :
Bruno Desthuilliers <br********************@wtf.websiteburo.oops.comwr ote
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_method with class list %s" % class_list
o = MyClass()
o.instance_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in instance_method
NameError: global name 'class_list' is not defined
The answer is in the error message. There's no local definition of
'class_list' in function 'instance_method', and no global definition of
'class_list' in the module. If you want to access MyClass.class_list in
function instance_method, you need to use a fully qualified name, ie
either self.class_list[1], self.__class__.class_list[2],
type(self).class_list[3] or MyClass.class_list[4]
[1] this one is ok in 'read mode' since attributes not found in the
instance's __dict__ will be looked up in the class's __dict__ (and then
in parent's classes __dict__), but be warned that something like
'self.class_list = []' will create an instance attribute of the same
name, shadowing the class one. This is one of the (in)famous Python gotchas.
[2] && [3] Those two ones are equivalent. [3] is cleaner since it avoids
direct access to an implementation attribute, but [2] is faster since it
avoids a function call. In both cases, the lookup will be what one would
expect in OO, that is first on the concrete class, then in the parents
classes.
[4] Only use this one if you really want to bypass inheritance.
On 2007-07-25, Alex Popescu <no*****************@gmail.comwrote:
Neil Cerutti <ho*****@yahoo.comwrote in news:eRwpi.36813$G23.28496
@newsreading01.news.tds.net:
>On 2007-07-25, Alex Popescu <no*****************@gmail.comwrote:
>>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.
I must confess that I am a bit confused by this advise, as both
are returning exactly the same thing.
Oops! I misthought myself.
I was thinking of MyClass.__dict__.keys() and
MyClass().__dict__.keys().
--
Neil Cerutti
To succeed in the world it is not enough to be stupid, you must also be well-
mannered. --Voltaire
On Wed, 25 Jul 2007 00:22:18 +0000, Alex Popescu wrote:
"Steven D'Aprano" <st***@REMOVE.THIS.cybersource.com.auwrote in
news:pa****************************@REMOVE.THIS.cy bersource.com.au:
>On Tue, 24 Jul 2007 21:35:58 +0000, Alex Popescu wrote:
>>Neil Cerutti <ho*****@yahoo.comwrote in news:sl********************@FIAD06.norwich.edu :
On 2007-07-24, Alex Popescu <no*****************@gmail.comwrote: Bruno Desthuilliers <br********************@wtf.websiteburo.oops.c omwrote in news:46***********************@news.free.fr: >
[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).
The whole point of inheritance is that you don't care where the attribute
is (the instance, the class, a parent class...) just that it exists.
--
Steven.
On Wed, 25 Jul 2007 00:55:17 +0000, Alex Popescu wrote:
Neil Cerutti <ho*****@yahoo.comwrote in news:eRwpi.36813$G23.28496
@newsreading01.news.tds.net:
>On 2007-07-25, Alex Popescu <no*****************@gmail.comwrote:
>>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.
I must confess that I am a bit confused by this advise, as both are
returning exactly the same thing.
>Preferably, the user of a class doesn't have to really think about it much.
I know that this would be prefered, but in case you are getting 3rd party
code and you modify a class attribute without knowing it is a class
attribute then you may get into trouble (indeed the real problem is with
the designer of the 3rd party code, but still I think it is a valid
concern).
# warning: doesn't consider slots
if "attribute" in instance.__dict__:
print "instance attribute"
elif "attribute" in instance.__class__.__dict__:
print "class attribute"
else:
print "either no attribute at all, or in a parent class"
--
Steven. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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()"
|
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
|
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):...
|
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...
|
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 =...
|
by: C Gillespie |
last post by:
Hi,
Does anyone know of any examples on how (& where) to use staticmethods and
classmethods?
Thanks
Colin
|
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
|
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...
|
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...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
| |