Object Oriented Programming
class Student(object): # 类名通常是大写开头的单词,object为继承类名 def __init__(self, name, score): # 必须绑定的属性 self.name = name self.score = score # 数据封装 def print_score(self): print('%s: %s' % (self.name, self.score)) bart = Student('Bart Simpson', 59) # 创建实例
在类中定义的函数,第一个参数永远是self,self指向创建的实例本身
访问限制
变量名以__开头,变为私有变量
获取对象信息
type()
isinstance()
dir() 获取对象的所有属性和方法
直接操作对象的状态
# 可以传入一个default参数,如果属性不存在,就返回默认值 hasattr(obj, 'x') # 有属性'x'吗? setattr(obj, 'y', 19) # 设置一个属性'y' getattr(obj, 'y') # 获取属性'y' obj.y # 获取属性'y'
实例属性和类属性
实例属性:通过self变量
类属性:直接定义,所有实例都可以访问
实例属性优先级比类属性高
绑定属性和方法
s = Student() s.name = 'Michael' # 动态给实例绑定一个属性 def set_age(self, age): # 定义一个函数作为实例方法 self.age = age from types import MethodType s.set_age = MethodType(set_age, s) # 给实例绑定一个方法 Student.set_age = set_age # 给类绑定方法
@property
将方法变成属性调用
class Student(object): @property def birth(self): # get_birth return self._birth @birth.setter # 不定义setter方法就是一个只读属性 def birth(self, value): # set_birth self._birth = value s.birth = 10 # 相当于s.set_birth(10) s.birth # 相当于s.get_birth()
多重继承
一个类同时继承多个类
“混入”额外的功能,使用MixIn(起名)
class Dog(Mammal, RunnableMixIn, CarnivorousMixIn): pass
定制类
使用__slot__
限制实例的属性
对继承子类无效,除非在子类定义__slot__
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
方法__str__
与__repr__
返回的对象描述信息
方法__iter__
与__next__
返回迭代对象
class Fib(object): def __init__(self): self.a, self.b = 0, 1 # 初始化两个计数器a,b def __iter__(self): return self # 实例本身就是迭代对象,故返回自己 def __next__(self): self.a, self.b = self.b, self.a + self.b # 计算下一个值 if self.a > 100000: # 退出循环的条件 raise StopIteration() return self.a # 返回下一个值
方法__getitem__
按下标取出元素
class Fib(object): def __getitem__(self, n): a, b = 1, 1 for x in range(n): a, b = b, a + b return a
方法__getattr__
当属性不存在时,返回属性
class Student(object): def __getattr__(self, attr): if attr=='score': return 99 # score属性不存在的时候返回 raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr) # 链式调用 REST API class Chain(object): def __init__(self, path=''): self._path = path def __getattr__(self, path): return Chain('%s/%s' % (self._path, path)) def __str__(self): return self._path __repr__ = __str__ Chain().status.user.timeline.list # '/status/user/timeline/list'
方法_call__
允许对实例进行调用
class Student(object): def __init__(self, name): self.name = name def __call__(self): print('My name is %s.' % self.name) s = Student('Michael') s() # My name is Michael.
枚举类
略
使用枚举类 – 廖雪峰的官方网站 (liaoxuefeng.com)
元类 metaclass
略