获取/更新对象属性:getattr/setattr
创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,当类示例较多时,就难以管理,这时需用使用__slots__来加强管理类的成员属性
类的__slots__用于显式地为对象绑定数据成员属性,并不针对每个实例自动生成__dict__和__weakref__,__slots__可以是字符串,可迭代对象或者以多个成员属性命名的字符串组成的序列,通过__slots__减少实例占用的内存空间。
class Test(object):
def __init__(self):
self.name = "Tom"
self.age = 20
if __name__ == '__main__':
tes = Test()
setattr(tes, "sex", "mail")
print(tes.__dict__)
# {'name': 'Tom', 'age': 20, 'sex': 'mail'}
使用__slots__之后:
__dict__属性丧失
class Test(object):
__slots__ = ("name", "age")
def __init__(self):
self.name = "Tom"
self.age = 20
if __name__ == '__main__':
tes = Test()
print(tes.__dict__)
# AttributeError: 'Test' object has no attribute '__dict__'
不能添加其他属性
class Test(object):
__slots__ = ("name", "age")
def __init__(self):
self.name = "Tom"
self.age = 20
if __name__ == '__main__':
tes = Test()
setattr(tes, "sex", "mail")
# AttributeError: 'Test' object has no attribute 'sex'
__slots__定义的属性仅对当前类实例起作用,对继承的子类不起作用
class Test(object):
__slots__ = ("name", "age")
def __init__(self):
self.name = "Tom"
self.age = 20
class Child(Test):
def __init__(self):
super(Child).__init__()
if __name__ == '__main__':
ch = Child()
setattr(ch, "sex", "mail")
print(ch.__dict__)
# {'sex': 'mail'}