1. 基本
class Student(object): name = 'Student' # 默认值 def __init__(self, name, score): self.score = score # public self.__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): pass def set_age(self, age): # 定义一个函数作为实例方法 self.age = age Student.set_score = set_score # 给Class增加function s = Student() s.set_score(100) # 可以调用
只给某个实例增加方法
from types import MethodType class Student(object): pass def set_age(self, age): # 定义一个函数作为实例方法 self.age = age s = Student() s.set_score= MethodType(set_score, s) # 给实例绑定一个方法 s.set_score(100) # 可以调用 s2 = Student() s2.set_score(100) # 不可以调用
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)
执行效果
('Jan', '=>', <Month.Jan: 1>, ',', 1) ...
枚举的其他例子
from enum import Enum, unique @unique class 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.Sun Mon => Weekday.Mon Tue => Weekday.Tue Wed => Weekday.Wed Thu => Weekday.Thu Fri => Weekday.Fri Sat => Weekday.Sat
参考资料
廖雪峰的Python教程
https://www.liaoxuefeng.com/