區分函數與方法

1、經過print打印區分

  • 函數在打印的時候,顯示的是function
  • 方法在打印的時候,顯示的是method
def func():
    pass

class Animal(object):

    def run(self):
        pass

print(func)  # <function func at 0x0000022343CD1F28>

c = Animal()
print(c.run)  # <bound method Animal.run of <__main__.Animal object at 0x0000022344128400>>

2、MethodType與FunctionType

1. 實例方法

  • 經過對象.方法名,獲得的是方法類型
  • 經過類名.方法名,獲得的是函數類型
from types import FunctionType, MethodType


class Foo(object):

    def run(self):
        pass


fn = Foo()
print(isinstance(fn.run, MethodType))     # True
print(isinstance(Foo.run, FunctionType))  # True

2. 靜態方法

  • 經過對象.方法名,獲得的是函數類型
  • 經過類名.方法名,獲得的是函數類型
from types import FunctionType, MethodType


class Foo(object):

    @staticmethod
    def run():
        pass

fn = Foo()
print(isinstance(fn.run, FunctionType))   # True
print(isinstance(Foo.run, FunctionType))  # True

 

3. 類方法

  • 經過對象.方法名,獲得的是方法類型
  • 經過類名.方法名,獲得的是方法類型
from types import FunctionType, MethodType


class Foo(object):

    @classmethod
    def run(cls):
        pass

fn = Foo()
print(isinstance(fn.run, MethodType))   # True
print(isinstance(Foo.run, MethodType))  # True
相關文章
相關標籤/搜索