绑定属性
class Student(object):
pass
s = Student()
s.name = 'ann' #给实例绑定属性
print(s.name)
_slots_限制实例属性
class Student(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
在创建实例之后,绑定实例属性score就会出错误。
s.age = 12
AttributeError: 'Student' object has no attribute 'age'
在这里age这个属性不在限制的范围内。
@property装饰器
将方法变成一个属性。
class Student(object):
@property #将score方法变成了属性,实例调用时,直接加.score
def score(self):
return self._score
@score.setter #将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 = 60 # 实际转化为s.set_score(60)
>>> s.score # 实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
...
ValueError: score must between 0 ~ 100!
练习:
请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution:
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self, value1):
self._width = value1
@property
def height(self):
return self._height
@height.setter
def height(self, value2):
self._height = value2
@property
def resolution(self):
return self.width * self.height
s = Screen()
s.width = 24
s.height = 8
print('s.resolution = ', s.resolution)
if s.resolution == 192:
print("测试通过")
else:
print("测试失败")
多重继承
主线通过单一继承下来,例如dog继承mammal,mammal继承animal,但是需要额外的的功能,通过多重继承实现,例如dog除了继承animal外还继承runable,这种设计成为Mixln。实际上就是给一个类增加多个功能。
定制类
str()方法,返回一个好看的字符串。
iter()方法,返回一个迭代对象,,不断调用该迭代对象的next()方法拿到虚幻的下一个值。用于for….in循环。
getitem()方法可当成list来使用。
如果要进行切片:
class Fib(object):
def __getitem__(self, n):
if isinstance(n, int): # n是索引
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
if isinstance(n, slice): # n是切片
start = n.start
stop = n.stop
if start is None:
start = 0
a, b = 1, 1
L = []
for x in range(stop):
if x >= start:
L.append(a)
a, b = b, a + b
return L
getattr()方法,可以返回不存在的属性。
call()方法,可以对实例直接进行调用。
class Student(object):
def __init__(self, name):
self.name = name
def __call__(self):
print('My name is %s.' % self.name)
结果是:
>>> s = Student('Michael')
>>> s() # self参数不要传入
My name is Michael.
PS:
class Student(object):
def __init__(self,name): #这里的属性常常忘记
self.name = name
s = Student('ann')
s.name #调用
结果:
Out[15]: 'ann'
限制访问:
class Student(object):
def __init__(self,name,score):
self._name = name #_name表示私有变量,只有内部可以访问,常常忘记加_
self._score = score
def get_name(self):
return self._name #从外部获取属性
s = Student('ann',90)
s.get_name() #调用get_name()方法
结果:
Out[15]: 'ann'