Python中区分函数和方法

1.简单粗暴型:

def func():
    ...
class Foo:
    def eat(self):
        print("吃")
f = Foo()
print(func) #<function func at 0x0000021527DAC1E0>
print(Foo.eat) #<function Foo.eat at 0x000001AE7FF6B268>
print(f.eat) #<bound method Foo.eat of <__main__.Foo object at 0x0000025711BD5EF0>>
# 通过类名调用的就是函数,通过类实例化的对象调用就是方法

2.导入模块判断:

from types import FunctionType,MethodType
def func():
    ...
class Foo:
    def eat(self):
        print("吃")
f = Foo()

print(isinstance(func,FunctionType)) # True
print(isinstance(f.eat,MethodType))  # True
print(isinstance(Foo.eat,FunctionType)) # True
print(isinstance(Foo.eat,MethodType)) # False

  

猜你喜欢

转载自www.cnblogs.com/changtao/p/10741787.html
今日推荐