一般情况下,单独写一个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函数类型
本文探讨了Python中函数与方法的概念差异。通过实例演示了在类内部定义的函数如何成为方法,以及它们之间的类型区别。文章解释了如何使用isinstance来判断函数与方法的类型。
6万+

被折叠的 条评论
为什么被折叠?



