函数和方法的区别
class Foo(object):
def fetch(self):
pass
Foo.fetch(123) # 函数
print(Foo.fetch)
# <function Foo.fetch at 0x00630BF8>
obj = Foo()
obj.fetch() # 方法
print(obj.fetch)
# <bound method Foo.fetch of <__main__.Foo object at 0x003FE550>>
from types import MethodType, FunctionType
class Foo(object):
def fetch(self):
pass
print(isinstance(Foo.fetch, MethodType)) # False
print(isinstance(Foo.fetch, FunctionType)) # True
obj = Foo()
print(isinstance(obj.fetch, MethodType)) # True
print(isinstance(obj.fetch, FunctionType)) # False
函数与方法的区别就是调用的对象不同,如果通过类去调用方法就是函数,如果通过一个对象去调用就是方法
浙公网安备 33010602011771号