1-给类动态增加方法
class Student(object): pass def set_score(self, score): self.score = score Student.set_score = set_score #动态给类增加方法 s = Student() s.set_score('dasheng') print(s.score) #dasheng
2-使用 __slots__ 限制实例属性
class Student(object): __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称 #使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的: #除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。
3- @property使用 (方便使用,属于装饰器)
class Student(object): @property #可读 def birth(self): return self._birth @birth.setter #可写 def birth(self, value): self._birth = value @property def age(self): #可读,由于没有age.setter方法,表示只读 return 2015 - self._birth s = Student() s.birth = 2011 #设置值 print(s.birth) #获取值
4-多重继承, 由于Python允许使用多重继承,因此,MixIn就是一种常见的设计。
class MyTCPServer(TCPServer, ForkingMixIn): pass
5-定制类
__str__(self) 或 __repr__() #让打印对象更好看 __iter__(self) #用于for ... in循环 def __iter__(self): return self # 实例本身就是迭代对象,故返回自己 __getitem__ #取下标 Fib()[5] def __getitem__(self, n): a, b = 1, 1 for x in range(n): a, b = b, a + b return a __getattr__() #当调用不存在的属性时,会试图调用__getattr__(self, 'score')来尝试获得属性 def __getattr__(self, attr): if attr=='age': return lambda: 25 __call__ #直接对实例进行调用 #通过callable()函数,我们就可以判断一个对象是否是“可调用”对象
介绍的是最常用的几个定制方法,还有很多可定制的方法,请参考Python的官方文档。
6-使用枚举
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)
6.1使用类创建
from enum import Enum, unique @unique class Weekday(Enum): Sun=0 Mon = 1, Tue = 2 day1 = Weekday.Mon print(day1 == Weekday.Tue)#False print(day1)#print(day1) print(day1.value) #print(day1)
7 使用元类创建
type()函数既可以返回一个对象的类型,又可以创建出新的类型
def fn(self, name='word'): print('hello %s' % name) Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class print(type(Hello)) #<class 'type'> h = Hello() print(type(h)) #<class '__main__.Hello'>
metaclass 魔术方法
class ListMetaclass(type): def __new__(cls, name, bases, attrs): attrs['add'] = lambda self, value: self.append(value) return type.__new__(cls, name, bases, attrs) class MyList(list, metaclass=ListMetaclass): pass __new__()方法接收到的参数依次是: 1.当前准备创建的类的对象; 2.类的名字; 3.类继承的父类集合; 4.类的方法集合。