how to tell a method is classmethod or static method or instance method
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Mon Feb 13 03:03:24 EST 2012
On Mon, 13 Feb 2012 15:59:27 +0900, Zheng Li wrote:
> how to tell a method is class method or static method or instance
> method?
That's a good question, with a subtle answer that depends on exactly what
you mean by the question. If you mean the object you get back from
ordinary attribute access like "instance.method", then you do this:
>>> class K(object):
... @classmethod
... def cmethod(cls):
... pass
... @staticmethod
... def smethod():
... pass
... def method(self):
... pass
...
>>> k = K()
>>> type(k.smethod)
<type 'function'>
So static methods are just functions, and both class methods and instance
methods share the same underlying type:
>>> type(k.method)
<type 'instancemethod'>
>>> type(k.cmethod)
<type 'instancemethod'>
But if you dig deeper, you learn that all methods are actually
descriptors:
>>> type(K.__dict__['cmethod'])
<type 'classmethod'>
>>> type(K.__dict__['smethod'])
<type 'staticmethod'>
>>> type(K.__dict__['method'])
<type 'function'>
(Functions are descriptors too.)
This is deep magic in Python, but if you want to learn more about it, you
can read this:
http://users.rcn.com/python/download/Descriptor.htm
And I'll take this opportunity to plug my dualmethod descriptor:
http://code.activestate.com/recipes/577030-dualmethod-descriptor/
--
Steven
More information about the Python-list
mailing list