10. 动态属性与 __slots__
Python 语言属于动态语言:在运行时可以改变其结构的语言,例如新的函数、对象、甚至代码可以被引进,已有的函数可以被删除。
在 Python 中,我们可以动态为对象添加属性,这是 Python 作为动态类型语言的一项特权。
python
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
stu = Student('王大锤', 20)
stu.sex = '男' # 给学生对象动态添加sex属性
如果不希望在使用对象时动态的为对象添加属性,可以使用 __slots__ 魔法:
python
class Student:
__slots__ = ('name', 'age')
def __init__(self, name, age):
self.name = name
self.age = age
stu = Student('王大锤', 20)
# AttributeError: 'Student' object has no attribute 'sex'
stu.sex = '男'