473,385 Members | 2,180 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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 17247
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******@hotmail.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(object):
"""
Base class for LDAP data objects.
"""

(snip)

# ------------------------------------------------------------------
def query_class(cls):
return "(objectClass=%s)" % cls.query_object_class
query_class = classmethod(query_class)

# ------------------------------------------------------------------
def query_id(cls, ldap_id):
return "(& %s (%s=%s))" % (cls.query_class(), cls.id_attribute,
ldap_id)
query_id = classmethod(query_id)

# ------------------------------------------------------------------
def query(cls, filters=None):
if filters is None:
return cls.query_class()
else:
return cls._decorate_query(filters(cls))
query = classmethod(query)

# ------------------------------------------------------------------
def _decorate_query(cls, query):
return "(& %s %s)" % (cls.query_class(), query)
_decorate_query = classmethod(_decorate_query)
class LdapContact(LdapObject):
"""
Wraps a MozillaAbPersonObsolete/OpenLDAPperson entry.
"""

# ldap objectClass(es)
object_classes =('OpenLDAPperson',
'MozillaAbPersonObsolete', )

# which one we'll use for queries
query_object_class = 'MozillaAbPersonObsolete'
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(self, entry) \
for entry in self._search( \
ldapItemKlass.query(filters, match_op) \
)]
if sort_keys is None:
sort_keys = ldapItemKlass.sort_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(self, 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(LdapContact, '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
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
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
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):...
1
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...
2
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
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
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...
0
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...
14
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...
1
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...
0
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...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.