學習廖雪峯官方網站python教程總結
python面向對象編程OOP(Object Oriented Programming)總結,供往後參考
1.類和實例python
#類的定義 class Student(object): #限制實例只能添加指定的屬性 __slots__ = ('sex','age') #類屬性 school = 'QingHua' #初始化值,建立實例必須綁定的屬性 def __init__(self,name,score): #private變量 self.__name = name self.__score = score #設置getter,setter保證類內部數據安全 def get_name(self): return self.__name def get_score(self): return self.__score def set_name(self,name): self.__name = name def set_score(self,score): self.__score = score def hello(self,name='world'): print('Hello, %s.' % name) #type()建立類,type()實質上是元類(metaclass),類的定義本質上就是利用type()建立類 def fn(self, name='world'): # 先定義函數 print('Hello, %s.' % name) Student = type('Student',(object,),dict(hello=fn)) #建立實例 jim = Student('Jim',120) print(jim.school) #QingHua print(jim.name) #Jim print(Student.school) #QingHua jim.age = 20 jim.height = 170 #報錯,不能添加__slots__未指定的屬性
2.@property
上例中,爲了保護內部數據的安全,咱們使用setter,getter方式封裝數據,可以防止用戶爲所欲爲地修改數據,可是不夠簡潔。使用@property裝飾器能夠幫助咱們改形成咱們想要的樣子編程
class Student(object): def __init__(self,birth): #private變量 self.__birth = birth @property def birth(self): return self.__birth @birth.setter def birth(self,value): self.__birth = value @property def age(self): return 2018-self.__birth #birth爲可讀寫屬性,age是隻讀屬性 s = Student(1995) s.birth #實際轉化爲s.get_birth 結果:1995 s.birth = 1996 #實際轉化爲s.set_birth s.age #22 s.age = 20 #報錯,當前age爲只讀屬性
3.繼承和多態安全
class Animal(object): def run(self): print('Animal is running') class Dog(Animal): def run(self): print('Dog is runing') class Cat(Animal): pass dog = Dog() cat = Cat() dog.run() #Dog is running Dog類重寫了Animal的run方法 cat.run() #Animal is running Cat類繼承了Animal的run方法 #多態 def run_log(obj): obj.run() run_log(Animal()) #Animal is running run_log(Dog()) #Dog is running #傳說中的file-like object class other(object): def run(): print('other is running') #傳入任何實現run方法的對象均可以,這就是動態語言多分魅力 run_log(other) #other is running
4.自定義類函數
#__str__讓class做用於print() class Student(object): def __init__(self,name): self.name = name def __str__(self): return 'Student name:%s' % self.name #__repr__用於調試服務,__str__用於用戶打印 __repr__ = __str__ print(Student('Tom')) # Student name:Tom #__iter__ #將class處理成tuple或list可迭代 class Fib(object): def __init__(self): self.a,slef.b = 0,1 def __iter__(self): return self def __next__(self): self.a,self.b = self.b,self.a+self.b if self.a>100 raise StopIteration() return self.a for n in Fib(): print(n) #1 1 2 3 5 8 13 21 34 55 89 #__getitem__() __getattr__() __call__()方法,之後用的時候具體瞭解
5.枚舉類學習
from enum import Enum Month = Enum('Month',('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')) for name,member in Month.__members__.items(): print(name,'=>',member,',',member.value) #value屬性自動賦給成員int變量,默認從1開始 #Enum派生自定義類 from enum import Enum,unique @unique class Weekday(Enum): Sun = 0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 #@unique裝飾器幫助咱們檢查保證沒有重複值