標籤:pre http set als last port get student mem
1. 基本
class Student(object): name = ‘Student‘ # 預設值 def __init__(self, name, score): self.score = score # publicself.__name = name # private def set_name(name): self.__name = name def get_name(): return self.__name
2.繼承
class Animal(object): def run(self): print(‘Animal is running...‘) class Dog(Animal): def run(self): print(‘Dog is running...‘)class Cat(Animal): def run(self): print(‘Cat is running...‘) def run_twice(animal): animal.run() animal.run()
運行樣本:
>>> run_twice(Animal())Animal is running...Animal is running...當我們傳入Dog的執行個體時,run_twice()就列印出:>>> run_twice(Dog())Dog is running...Dog is running...當我們傳入Cat的執行個體時,run_twice()就列印出:>>> run_twice(Cat())Cat is running...Cat is running...
多態的好處就是:傳參是誰,就調用誰的方法。彼此有繼承關係。
object是所有類的繼承父類。
3.判斷繼承關係
dog = Dog()print(isinstance(dog, Animal)) # Animal
True
4.動態綁定函數
class Student(object): passdef set_age(self, age): # 定義一個函數作為執行個體方法 self.age = ageStudent.set_score = set_score # 給Class增加functions = Student()s.set_score(100) # 可以調用
只給某個執行個體增加方法
from types import MethodTypeclass Student(object): passdef set_age(self, age): # 定義一個函數作為執行個體方法 self.age = ages = Student()s.set_score= MethodType(set_score, s) # 給執行個體綁定一個方法s.set_score(100) # 可以調用s2 = Student()s2.set_score(100) # 不可以調用
5.枚舉
from enum import EnumMonth = 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)
執行效果
(‘Jan‘, ‘=>‘, <Month.Jan: 1>, ‘,‘, 1)...
枚舉的其他例子
from enum import Enum, unique@uniqueclass Weekday(Enum): Sun = 0 # Sun的value被設定為0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6
執行結果
>>> day1 = Weekday.Mon>>> print(day1)Weekday.Mon>>> print(Weekday.Tue)Weekday.Tue>>> print(Weekday[‘Tue‘])Weekday.Tue>>> print(Weekday.Tue.value)2>>> print(day1 == Weekday.Mon)True>>> print(day1 == Weekday.Tue)False>>> print(Weekday(1))Weekday.Mon>>> print(day1 == Weekday(1))True>>> Weekday(7)Traceback (most recent call last): ...ValueError: 7 is not a valid Weekday>>> for name, member in Weekday.__members__.items():... print(name, ‘=>‘, member)...Sun => Weekday.SunMon => Weekday.MonTue => Weekday.TueWed => Weekday.WedThu => Weekday.ThuFri => Weekday.FriSat => Weekday.Sat
參考資料
廖雪峰的Python教程
https://www.liaoxuefeng.com/
Python物件導向