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

  

posted @ 2019-04-20 17:36  Py浪涛  阅读(376)  评论(0编辑  收藏  举报
你想听歌吗o((;=゚ 3゚ =))o~♪