“`” 看他的调用者是谁,如果是类,就需要传入一个参数self的值,这时他就是一个函数,
如果调用者是对象,就不需要给self传入参数值,这时他就是一个方法
print(isinstance(obj.func, FunctionType)) # False
print(isinstance(obj.func, MethodType)) # True
<pre><code>class Foo(object):
def __init__(self):
self.name = 'lcg'
def func(self):
print(self.name)
obj = Foo()
print(obj.func) # <bound method Foo.func of <__main__.Foo object at 0x000001ABC0F15F98>>
print(Foo.func) # <function Foo.func at 0x000001ABC1F45BF8>
# ————————FunctionType, MethodType————#
from types import FunctionType, MethodType
obj = Foo()
print(isinstance(obj.func, FunctionType)) # False
print(isinstance(obj.func, MethodType)) # True
print(isinstance(Foo.func, FunctionType)) # True
print(isinstance(Foo.func, MethodType)) # False
# ————————————————————#
obj = Foo()
Foo.func(obj) # lcg
obj = Foo()
obj.func() # lcg
""""""
注意:
方法,无需传入self参数
函数,必须手动传入self参数
""""""
</code></pre>
<pre><code> "“`
Was this helpful?
0 /
0