python3中如何区分一个函数和方法

时间:2023-03-09 08:52:56
python3中如何区分一个函数和方法

一般情况下,单独写一个def func():表示一个函数,如果写在类里面是一个方法。但是不完全准确。

class Foo(object):
def fetch(self):
pass print(Foo.fetch) # 打印结果<function Foo.fetch at 0x000001FF37B7CF28>表示函数
# 如果没经实例化,直接调用Foo.fetch()括号里要self参数,并且self要提前定义
obj = Foo()
print(obj.fetch) # 打印结果<bound method Foo.fetch of <__main__.Foo object at 0x000001FF37A0D208>>表示方法
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 # MethodType方法类型
# FunctionType函数类型

相关文章