python 面向对象高级编程

来源:互联网 发布:疯狂原始人 知乎 编辑:程序博客网 时间:2024/05/16 08:48
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.heights = Screen()s.width = 1024s.height = 768print(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 = 2s.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 MethodTypeclass Student():    passs=Student()s.age=10def set_age(self,age):     self.age = agedef get_age(self):    return self.ages.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 EnumMonth = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))

@unique装饰器可以帮助我们检查保证没有重复值。



元类


原创粉丝点击