0
点赞
收藏
分享

微信扫一扫

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

和谐幸福的人生 2022-08-22 阅读 60

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

class Foo(object):
def fetch(self):
pass

print(Foo.fetch) #function
# 如果没经实例化,直接调用Foo.fetch()括号里要self参数,并且self要提前定义
obj = Foo()
print(obj.fetch) #method

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函数类型

 



举报

相关推荐

0 条评论