__slots__属性可以设置 允许被设置的属性
class Student:
__slots__ = ("name", "age")
>>> s = Student() >>> s.age = >>> s.name = "Zoro" >>> s.score =
Traceback (most recent call last):
File "<ipython-input-38-b5a9e82f869f>", line , in <module>
s.score = AttributeError: 'Student' object has no attribute 'score'
当一个类中设置__slots__属性时,只有()中的属性可以动态设置
@property装饰器
class Student():
@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 < or value > :
raise ValueError("Score must between 0~100!")
self._score = value @score.deleter
def score(self):
del self._score
>>> s = Student()
>>> s.score =
>>> s.score
Out[]: 100
>>> s.score =
Traceback (most recent call last):
File "<ipython-input-44-84f4bf77cd8e>", line , in <module>
s.score =
File "C:/Users/SQD/Desktop/@property.py", line , in score
raise ValueError("Score must between 0~100!")
ValueError: Score must between ~! >>> s.score = "abc"
Traceback (most recent call last):
File "<ipython-input-45-179a51b0c6cf>", line , in <module>
s.score = "abc"
File "C:/Users/SQD/Desktop/@property.py", line , in score
raise ValueError("Score must be an integer!")
ValueError: Score must be an integer! >>> del s.score
把一个getter方法变成属性,只需要加上@property
就可以了,此时,@property
本身又创建了另一个装饰器@score
还可以设置只读属性:只有getter,没有setter
class Student:
@property
def birth(self):
return self._birth
@birth.setter
def birth(self, value):
self._birth = value @property
def age(self):
return - self._birth
>>> s = Student()
>>> s.birth =
>>> s.age
Out[]: >>> s.age =
Traceback (most recent call last):
File "<ipython-input-58-03895bf010a3>", line , in <module>
s.age = AttributeError: can't set attribute