python---面向對象高級進階
阿新 • • 發佈:2017-08-14
刪除數據 name 兩個 構造 hasattr def method res 錯誤類型
靜態方法,調用靜態方法後,該方法將無法訪問類變量和實例變量
1 class Dog(object): 2 def __init__(self,name): 3 self.name = name 4 5 def eat(self,food): 6 print("%s is eating %s"%(self.name,food)) 7 8 d = Dog("Jack") 9 d.eat("banana") 10 11 #靜態方法寫法 12 class Dog(object): 13 def __init__(self,name):14 self.name = name 15 @staticmethod #靜態類後,則無法調用類變量和實例變量 16 def eat(self): #需要傳進來的是實例了,而不能調用類本身的屬性 17 print("%s is eating %s"%(self.name,"banana")) 18 19 d = Dog("Alex") 20 d.eat(d) #傳入實例化後的一個實例
類方法,類方法後,可以訪問類變量,但無法訪問實例變量
1 class Dog(object): 2 name = "Mark" 3 def __init__(self,name): 4 self.name = name 5 @classmethod 6 def eat(self): 7 print("%s is eating %s"%(self.name,"banana")) #name為類變量,而非實例變量 8 9 d = Dog("Alex") 10 d.eat() 11 #運行結果:Mark is eating banana
屬性方法,@property 調用屬性方法後,該方法將是靜態屬性,調用不需要加(),直接調用即可
1class Dog(object): 2 def __init__(self,name): 3 self.name = name 4 self.__food = None 5 @property 6 def eat(self): 7 print("%s is eating %s"%(self.name,"banana")) 8 @eat.setter 9 def eat(self,food): 10 print("set food:",food) 11 self.__food = food 12 13 d = Dog("Alex") 14 d.eat #屬性方法輸出的是屬性,不需要動態調用,即不需要d.eat()
屬性方法修改,刪除
class Dog(object): def __init__(self,name): self.name = name self.__food = None @property def eat(self): print("%s is eating %s"%(self.name,self.__food)) @eat.setter def eat(self,food): #修改屬性方法的參數 print("set food:",food) self.__food = food @eat.deleter #刪除屬性方法的參數 def eat(self): del self.__food print("deleted!!!!!") d = Dog("Mark") d.eat d.eat = "apple" #向屬性方法種傳遞參數 d.eat del d.eat #刪除屬性方法種的參數 d.eat
__metaclass__,__init___,__call__,__new__方法調用
1 # -*- coding:utf-8 -*- 2 # LC 3 4 class MyType(type): 5 def __init__(self,*args,**kwargs): 6 print("Mytype init",args,kwargs) 7 def __call__(self, *args, **kwargs): 8 print("Mytype call",args,kwargs) 9 obj = self.__new__(self) 10 self.__init__(obj,args,kwargs) 11 12 class Foo(object): 13 __metaclass__ = MyType #表示該類是由誰來實例化自己的(即Foo類) 14 def __init__(self): 15 print("foo init") 16 def __new__(cls, *args, **kwargs): 17 print("foo new") 18 return object.__new__(cls) 19 20 f = Foo() 21 #在python2或者3中,執行順序為:__new__ , __init__, __call__、 22 #__new__優於__init__執行 23 #__call__用於創建__new__
反射,類的反射
1 class Dog(object): 2 def __init__(self,name): 3 self.name = name 4 5 def eat(self): 6 print("%s is eating"%self.name) 7 8 def bulk(self): 9 print("%s is yelling"%self.name) 10 11 12 d = Dog("Jack") 13 14 choice = input(">>:").strip() 15 print(hasattr(d,choice)) #表示對象中是否含有choice的屬性,包含變量,方法等 16 17 if hasattr(d,choice): 18 print(getattr(d,choice)) #獲取對象中的choice屬性,如果是變量,則獲取變量值,如果是方法,可以通過加()進行執行 19 getattr(d,choice)() 20 else: 21 setattr(d,choice,bulk) #設置對象中的choice屬性,如可以新增一個變量或方法 22 getattr(d,choice)(d) #func = get(d,choice), func(d) 23 d.talk(d) 24 25 delattr(d,choice) #刪除對象中的choice屬性,可以是變量,也可以是方法 26 d.talk(d)
類的特殊方法:
1 # -*- coding:utf-8 -*- 2 # LC 3 4 #__doc__ 輸出類的描述信息 5 class Foo: 6 ‘‘‘ 7 類的描述信息 8 ‘‘‘ 9 def func(self): 10 pass 11 12 print(Foo.__doc__) 13 14 15 #__module__ 輸出當前操作的對象在那個模塊 16 #__class__ 輸出當前操作的對象的類是什麽 17 18 from lib.aa import C 19 obj = C() 20 print(obj.__module__) 21 print(obj.__class__) 22 23 #__call__ 對象後加括號,觸發執行 24 #構造方法的執行是由創建對象觸發的,即:對象=類名();而對於__call__方法的執行是由對象加括號觸發的,即對象()或類()() 25 class Dog(object): 26 def __init__(self,name): 27 self.name = name 28 29 def __call__(self, *args, **kwargs): 30 print("%s running call"%self.name,args,kwargs) 31 32 obj2 = Dog("alex") 33 obj2("wawawa",sex="F") 34 35 36 #__dict__ 查看類或者對象中的成員 37 38 print(Dog.__dict__) 39 print(obj2.__dict__) 40 41 #__str__ 如果一個類中定義了__str__方法,則在打印對象的時候,默認輸出該方法(__str__)的值 42 class Cat(object): 43 def __str__(self): 44 return "str method" 45 46 obj3 = Cat() 47 print(obj3) 48 49 #__getitem__,__setitem__,__delitem__ 用於索引操作,如字典,分別進行獲取,設置,刪除數據 50 51 class apple(object): 52 def __init__(self): 53 self.data = {} 54 def __getitem__(self, key): 55 print("get apple %s"%key) 56 return self.data.get(key) 57 def __setitem__(self, key, value): 58 print("setting apple,%s,%s"%(key,value)) 59 self.data[key] = value 60 def __delitem__(self, key): 61 print("deleting apple %s"%key) 62 del self.data[key] 63 64 obj4 = apple() 65 obj4["apple1"] = "red" 66 obj4["apple2"] = "green" 67 68 res = obj4["apple1"] 69 print(‘---‘,res) 70 print(obj4.data) 71 del obj4["apple1"] 72 res = obj4["apple2"] #刪除後則沒有了。輸出為None,具體是否刪除,也是由__delitem__方法定義的 73 print(‘---‘,res) 74 75 76 #__new__ 77 class Foo(object): 78 def __init__(self,name): 79 self.name = name 80 81 f = Foo("Jack") 82 print(type(f)) 83 print(type(Foo))
異常處理
1 names = ["Alex","Jack"] 2 dict = {} 3 4 try: 5 names[3] 6 except IndexError as e: #抓具體的錯誤類型 7 print("ERROR !!!",e) 8 9 try: 10 names[3] 11 except Exception as e: #包含所有的錯誤類型,不建議使用,建議使用在最後抓未知錯誤 12 print("ERROR !!!",e) 13 14 15 16 try: 17 dict["age"] 18 except KeyError as e: #抓具體的錯誤類型 19 print("ERROR !!!",e) 20 21 try: 22 #dict["age"] 23 #names[3] 24 print(names[3]) 25 except (IndexError,KeyError) as e: #抓取兩個錯誤中的任意一個,代碼誰先出錯則執行誰 26 print("ERROR",e) 27 else: #沒有錯的時候執行 28 print("all is well") 29 30 finally: #不管有沒有錯,都執行 31 print("不管有你沒有錯,都執行") 32 33 34 class TestException(Exception): #自定義異常 35 def __init__(self,msg): 36 self.msg = msg 37 38 try: 39 raise TestException(‘自定義異常‘) 40 except TestException as e: 41 print(e)
python---面向對象高級進階