python 装饰器@property使用
class Screen(): @property def width(self): return self._width pass @width.setter def width(self,value): self._width=value @property def height(self): return self._height @width.setter def height(self,value): self._height=value @property def resolution(self): return self.width*self.height s = Screen() s.width = 1024 s.height = 768 print(s.resolution) assert s.resolution == 786432, '1024 * 768 = %d ?' % s.resolution
python _slots_使用
限制实例的属性,限制属性仅对当前类的实例有效。
class Student(object): __slots__ = ('name','age') s=Student() s.name = '张三' s.age = 2 s.sex='boy'
Traceback (most recent call last):
File "/home/caidong/developProgram/learnDemo/phantomJsDemo/Slots.py", line 7, in <module>
s.sex='ds'
AttributeError: 'Student' object has no attribute 'sex'
python 实例动态添加属性和方法
from types import MethodType class Student(): pass s=Student() s.age=10 def set_age(self,age): self.age = age def get_age(self): return self.age s.set_age=MethodType(set_age,s) s.get_age = MethodType(get_age,s) s.set_age(1) b=s.get_age() print(s.age) print(b)
python 多继承
Mixin 同时继承多个类
python 定制类 特殊函数的
_str_ __iter__ __getitem__ __getattr__
__call__
python 枚举类
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
@unique
装饰器可以帮助我们检查保证没有重复值。
元类