class Animal: def eat(self): print('動物的世界你不懂') class Cat(Animal): def play(self): print('毛霸王') c = Cat() print(isinstance(c,Cat)) # True # 向上判斷 print(isinstance(c,Animal)) # True a = Animal() print(isinstance(a,Cat)) # False # 不能向下判斷 print(type(a)) # <class '__main__.Animal'> print(type([])) # <class 'list'> print(type(c)) # <class '__main__.Cat'> # 判斷 **類是不是**類的子類 print(issubclass(Cat,Animal)) # True print(issubclass(Animal,Cat)) # False
def cul(a,b): if (type(a) == int or type(a) == float) and (type(b) == int or type(b) == float): return a+b else: print('提供的數據沒法計算') print(cul(6,7))
def func(): print('我是函數') class Foo: def eat(self): print('要吃飯了') print(func) # <function func at 0x0000020EDE211E18> f = Foo() f.eat() print(f.eat) # <bound method Foo.eat of <__main__.Foo object at 0x00000237390BE358>>
# 類也是對象 # 這個對象:屬性就是類變量 # 方法就是類方法 class Person(): def eat(self): print('明天去吃魚') @classmethod def he(cls): print('我是類方法') @staticmethod def lang(): print('我是靜態方法') p = Person() Person.eat(1) # 不符合面向對象的思惟 print(p.eat) # <bound method Person.eat of <__main__.Person object at 0x00000253E992E3C8>> print(Person.eat) # <function Person.eat at 0x00000253E992DF28> # 類方法都是方法 print(Person.he) # <bound method Person.he of <class '__main__.Person'>> print(p.he) # <bound method Person.he of <class '__main__.Person'>> # 靜態方法都是函數 print(Person.lang) # <function Person.lang at 0x0000024C942F1158> print(p.lang) # <function Person.lang at 0x0000024C942F1158>
def eat(): print('吃遍人間美味') def travel(): print('遊遍萬水千山') def see(): print('看遍人間繁華') def play(): print('玩玩玩') def learn(): print('好好學習每天向上')
import master while 1: content = input('請輸入你要測試的功能:') # 判斷 XXX對象中是否包含了xxx if hasattr(master,content): s = getattr(master,content) s() print('有這個功能') else: print('沒有這個功能')
class Foo: def drink(self): print('要少喝酒') f = Foo() s = (getattr(f,'drink')) # 從對象中獲取到str屬性的值 s() print(hasattr(f,'eat')) # 判斷對象中是否包含str屬性 setattr(f,'eat','西瓜') # 把對象中的str屬性設置爲value print(f.eat) setattr(f,'eat',lambda x:x+1) print(f.eat(3)) print(f.eat) # 把str屬性從對象中刪除 delattr(f,"eat") print(hasattr(f,'eat'))