how to tell a method is classmethod or static method or instance method

88888 Dihedral dihedral88888 at googlemail.com
Mon Feb 13 10:01:33 CET 2012


在 2012年2月13日星期一UTC+8下午4时03分24秒,Steven D'Aprano写道:
> 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

The methods of an object can be well organized
to avoid redundant checks of operations 
desired to be performed on the object.

Also an object's methods should be factored to be easy to be maintained
 and to provide debugging and error information for the programmer to track
the operations related to the hardware, the OS, and the sofware design
issues. 







More information about the Python-list mailing list