您的位置:首页 > 编程语言 > Python开发

python 面向对象高级编程

2017-08-04 21:51 302 查看
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
装饰器可以帮助我们检查保证没有重复值。

元类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: