from types import FunctionType, MethodType
class Car(object):
def __init__(self):
pass
def run(self):
print("my car can run!")
@staticmethod
def fly(self):
print("my car can fly!")
@classmethod
def jumk(cls):
print("my car can jumk!")
c = Car()
# type(obj) 表示查看obj是由哪個類創建的.
# 實例方法
print(type(c.run)) # <class 'method'>
print(type(Car.run)) # <class 'function'>
# 靜態方法
print(type(c.fly)) # <class 'function'>
print(type(Car.fly)) # <class 'function'>
# 類方法,因為類在內存中也是對象,所以調用類方法都是方法類型
print(type(c.jumk)) # <class 'method'>
print(type(Car.jumk)) # <class 'method'>
# 使用FunctionType, MethodType 來判斷類型
# 實例方法
print(isinstance(c.run,MethodType)) # True
print(isinstance(Car.run,FunctionType)) # True
# 靜態方法
print(isinstance(c.fly,FunctionType)) # True
print(isinstance(Car.fly,FunctionType)) # True
# 類方法
print(isinstance(c.jumk,MethodType)) # True
print(isinstance(Car.jumk,MethodType)) # True
"""結論
1. 類⽅法.不論任何情況,都是⽅法.
2. 靜態方法,不論任何情況.都是函數
3. 實例方法,如果是實例訪問.就是⽅法.如果是類名訪問就是函數.
"""