代码
不知道之前是复制哪位博主的,if 你知道的话,请告诉我,我一定附上原链接
def the_function():
pass
class TheClass:
def __call__(self, *args, **kwargs):
return self
@classmethod
def class_method(cls):
pass
def instance_method(self):
return self
@staticmethod
def static_method():
pass
@test_decorator
def decorated_func(self):
pass
if __name__ == '__main__':
the_class = TheClass()
print('class_method type {type} '.format(type=type(TheClass.class_method)))
# class_method type <class_ 'method'>
print('instance_method type {type} '.format(type=type(the_class.instance_method)))
# instance_method type <class_ 'method'>
print(TheClass.class_method)
# <bound method TheClass.class_method of <class '__main__.TheClass'>>
print(the_class.instance_method)
# <bound method TheClass.instance_method of <__main__.TheClass object at 0x00000275DEB3FC50>>
print('instance_method type {type} '.format(type=type(TheClass.instance_method)))
# instance_method type <class 'function'>
print(TheClass.instance_method)
# <function TheClass.instance_method at 0x00000275DEB3D840>
print('static_method type {type} '.format(type=type(the_class.static_method)))
# static_method type <class_ 'function_'>
print('static_method type {type} '.format(type=type(TheClass.static_method)))
# static_method type <class 'function'>
print(TheClass.static_method, the_class.static_method, sep='\n')
# <function TheClass.static_method at 0x0000024BC5EAD950>
# <function TheClass.static_method at 0x0000024BC5EAD950>
print('the_function type {type} '.format(type=type(the_function)))
# the_function type <class_ 'function_'>
print('test_decorator type {type} '.format(type=type(test_decorator)))
# test_decorator type <class_ 'function_'>
print('decorated_func type {type} '.format(type=type(the_class.decorated_func)))
# decorated_func type <class_ 'method'>
print('class_instance callable {callable} '.format(callable=callable(the_class)))
print('class_instance type {type} '.format(type=type(the_class)))
# class_instance type <class_ '__main__.TheClass'>
总结
- 函数(function)是Python中一个可调用对象(callable), 方法(method)是一种特殊的函数
- 一个可调用对象是方法和函数,和这个对象(例如类方法、实例方法、静态方法或者外部函数)无关
- 静态方法没有和任何类或实例绑定,所以静态方法是个函数
- 类实现__call__方法,实例的类型依旧是这个类,而不会变成函数或方法
class_instance type <class_ '__main__.TheClass'>
- 判断对象是函数或方法应该使用type(obj)
- 当一个实例方法,通过
类
去访问时,因为不存在绑定关系,它是函数. 通过类的实例化对象去访问时,存在绑定关系,那么它就成了方法。 - 对于一个装饰器函数,因为不会和任何类或实例绑定(除非使用MethodType将函数绑定到某个实例上),必然不是方法。装饰器不会改变被装饰函数或方法的类型
print(TheClass.class_method)
<bound method TheClass.class_method of <class '__main__.TheClass'>>