点我
多重继承&限制实例
限制实例属性:\_slots_
为了达到限制实例属性的目的,Python允许在定义class的时候,定义一个特殊的\__slots__变量,来限制该class实例能添加的属性
注意:\__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
class Student(object):
__slots__ = ('name','age')
s = Student()
s.name = 'zs'
s.age = 20
s.score = 20
#AttributeError: 'Student' object has no attribute 'score'
# 不能被执行
@property
在绑定属性时,如果我们直接把属性暴露出去,虽然编写简单,但是没办法检查参数,导致可以把成绩随便改
@property装饰器就是负责把一个方法变成属性调用的
注意:@property,我们在对实例属性操作的时候,就知道该属性很可能不是直接暴露的,而是通过getter和setter方法来实现的
class Student():
@property
def score(self):
print(self._score)
# @property本身又创建了另一个装饰器 @ score.setter
# 负责把一个setter方法变成属性赋值
@score.setter
def score(self,value):
if not isinstance(value,int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
s = Student()
s.score = 70
s.score
多重继承
在设计类的继承关系时,通常,主线都是单一继承下来的,但是,如果需要“混入”额外的功能,通过多重继承就可以实现
MixIn
为了更好地看出继承关系,通常在增加的其他继承类名后加上MixIn
MixIn的目的就是给一个类增加多个功能,在设计类的时候,我们优先考虑通过多重继承来组合多个MixIn的功能,而不是设计多层次的复杂的继承关系
class MyTCPServer(TCPServer, ForkingMixIn):
pass
分类:
Python
版权申明
本文系作者 @小白学安全 原创发布在 xbxaq.com 站点,未经许可,禁止转载!
评论