Z
Zheng Li
how to tell a method is class method or static method or instance method?
how to tell a method is class method or static method or instance
method?
<type 'function'>type(K.__dict__['cmethod'])type(K.__dict__['smethod'])type(K.__dict__['method'])
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:
... @classmethod
... def cmethod(cls):
... pass
... @staticmethod
... def smethod():
... pass
... def method(self):
... pass
... <type 'function'>
So static methods are just functions, and both class methods and instance
methods share the same underlying type:
<type 'instancemethod'>
But if you dig deeper, you learn that all methods are actually
descriptors:
<type 'function'>type(K.__dict__['cmethod'])type(K.__dict__['smethod'])type(K.__dict__['method'])
(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/
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.