473,591 Members | 2,810 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

staticmethod and classmethod

Hi,

Does anyone know of any examples on how (& where) to use staticmethods and
classmethods?

Thanks

Colin
Jul 19 '05 #1
5 17259
Think I read something about it here:

http://heather.cs.ucdavis.edu/~matloff/Python/

not sure though.

Lorenzo

Jul 19 '05 #2
C Gillespie wrote:
Does anyone know of any examples on how (& where) to use staticmethods and
classmethods?


My personal experience is that I almost *never* want a staticmethod.
The things that I would have written as a staticmethod in Java I simply
write as a module-level function in Python.

I do occasionally used classmethods though to build alternate
constructors. I recently had a class with a constructor that looked like:

class C(object):
def __init__(self, *args):
...

I already had code working with this constructor, but I needed to add an
optional 'index' parameter. I found the clearest way to do this was
something like:

class C(object):
def __init__(self, *args):
...
@classmethod
def indexed(cls, index, *args):
...
obj = cls(*args)
obj.index = index
...
return obj

Then the classes that needed the 'index' parameter simply use
C.indexed() as the constructor instead of C().

STeVe
Jul 19 '05 #3
"C Gillespie" <cs******@hotma il.com> wrote in message
news:d6******** **@ucsnew1.ncl. ac.uk...
Hi,

Does anyone know of any examples on how (& where) to use staticmethods and
classmethods?
A python class method is closer to a Java static method than a python static
method.
Class methods can be useful if you want to be able to change objects in the
class, or if you want to be able to use inheritance, neither of which python
static
methods allow you to do cleanly.

Another, and rather esoteric use, is to use the class as its own instance.

I find that static methods are useful when I want to import a class from
a module, and don't want to import the module itself or a lot of bits and
pieces from the module. The class gives a place to park the method, and
also lets you use inheritance, neither of which putting it into the module
does.

John Roth
Thanks

Colin


Jul 19 '05 #4
C Gillespie a écrit :
Hi,

Does anyone know of any examples on how (& where) to use staticmethods and
classmethods?


Here's an example from a ldap lib (work in progress, not finished, and
all other disclaimers).

The class methods are here:

# ----------------------------------------------------------------------
# Base class for LDAP Objects
# ----------------------------------------------------------------------
class LdapObject(obje ct):
"""
Base class for LDAP data objects.
"""

(snip)

# ------------------------------------------------------------------
def query_class(cls ):
return "(objectClass=% s)" % cls.query_objec t_class
query_class = classmethod(que ry_class)

# ------------------------------------------------------------------
def query_id(cls, ldap_id):
return "(& %s (%s=%s))" % (cls.query_clas s(), cls.id_attribut e,
ldap_id)
query_id = classmethod(que ry_id)

# ------------------------------------------------------------------
def query(cls, filters=None):
if filters is None:
return cls.query_class ()
else:
return cls._decorate_q uery(filters(cl s))
query = classmethod(que ry)

# ------------------------------------------------------------------
def _decorate_query (cls, query):
return "(& %s %s)" % (cls.query_clas s(), query)
_decorate_query = classmethod(_de corate_query)
class LdapContact(Lda pObject):
"""
Wraps a MozillaAbPerson Obsolete/OpenLDAPperson entry.
"""

# ldap objectClass(es)
object_classes =('OpenLDAPpers on',
'MozillaAbPerso nObsolete', )

# which one we'll use for queries
query_object_cl ass = 'MozillaAbPerso nObsolete'
id_attribute = 'uid'
sort_keys = ('displayName', )

(snip)
They are used here (LdapItemKlass is supposed to be a subclass of
LdapObject, like LdapContact above):

# ----------------------------------------------------------------------
# The LdapConnection itself.
# ----------------------------------------------------------------------
class LdapConnection( object):

(snip)

# ------------------------------------------------------------------
def list_items(self , ldapItemKlass, sort_keys=None,
filters=None):
items = [ldapItemKlass(s elf, entry) \
for entry in self._search( \
ldapItemKlass.q uery(filters, match_op) \
)]
if sort_keys is None:
sort_keys = ldapItemKlass.s ort_keys
return self.sort(items , sort_keys)

# ------------------------------------------------------------------
def get_item(self, ldapItemKlass, ldap_id):
entry = self._get_item( ldapItemKlass, ldap_id)
if entry is not None:
entry = ldapItemKlass(s elf, entry)
return entry

(snip)
And client code may look like this (LdapContact being a subclass of
LdapObject):

cnx = LdapConnection( ...).connect()
all_contacts = cnx.list_items( LdapContact)
someone = cnx.get_item(Ld apContact, 'uid=someone')
Since we don't have any instance before running the query, we can't use
instance methods... Still, most of the knowledge required to build the
appropriate query belongs to the LdapContact (or whatever) class.

HTH
Bruno
Jul 19 '05 #5
[Bruno Desthuilliers]
C Gillespie a écrit :
Does anyone know of any examples on how (& where) to use
staticmethods and classmethods?

Here's an example from a ldap lib [...]


I recently had a use case for class methods while converting a PL/I
program to Python: a lot of global declarations, where in many cases,
procs could be regrouped around well identified subsets of globals.

The idea is to create a class for each related group of globals. The
global declarations themselves become class variables of that class, and
related procs become class methods meant to act on these class variables.

For best clarity and legibility while doing so, one should use all
lowercase class names in such cases, and use `self' instead of `cls' for
the first formal argument of class methods[1].

Then, one use these classes as if they were each the single instance
of a similar class with usual methods. If one later changes his/her
mind and wants more usual objects, and not allocated statically (!),
merely remove all classmethod declarations, capitalise the first letter
of class names, and create one instance per class into the all lowercase
name of the class. That's seemingly all.

--------------

[1] I already found out a good while ago, in many other cases unrelated
to this one, but notably in metaclasses, that `self' is often (not
always) clearer than `cls'. Classes are objects, too! :-)

--
François Pinard http://pinard.progiciels-bpi.ca
Jul 19 '05 #6

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...
2
1876
by: Neal Becker | last post by:
How can I write code to take advantage of new decorator syntax, while allowing backward compatibility? I almost want a preprocessor. #if PYTHON_VERSION >= 2.4 @staticmethod ....
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
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
1298
by: Steven Bethard | last post by:
Steven Bethard wrote: > (For anyone else out there reading who doesn't already know this, > Steven D'Aprano's comments are easily explained by noting that the > __get__ method of staticmethod objects returns functions, and classes > always call the __get__ methods of descriptors when those descriptors > are class attributes: Steven D'Aprano wrote: > Why all the indirection to implement something which is, conceptually, > the same as an...
14
2721
by: james_027 | last post by:
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?
0
8362
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
7992
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
8225
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
5732
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
3850
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...
0
3891
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2378
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
1
1465
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1199
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.