Python学习笔记:面向对象高级编程
学自廖雪峰巨佬的Python3教程:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143186738532805c392f2cc09446caf3236c34e3f980f000
1.前面讲到过,可以给对象和类绑定方法,但是如果想要限制对象的属性,比如只允许对Student实例添加name和age属性,就可以在定义Class的时候,定义一个特殊的__slots__变量来进行限制
class Student(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的,除非在子类中也定义
2.之前提到可以用getter和setter方法来获取数据,但是又没有直接获取属性这么简单,Python内置的@property装饰器就是负责把一个方法变成属性调用的
class Student(object):
@property
def score(self):
return self._score
@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 = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
...
ValueError: score must between 0 ~ 100!
把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
@property
def height(self):
return self._height
@height.setter
def height(self, value):
self._height = value
@property
def resolution(self):
return self._height * self._width
# 测试:
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution ==