问题描述
class Toy():
def __init__(self,color,age):
self.color = color
self.age = age
self.my_dict = {
'name':'Yoyo','has_pets': False,}
def __setattr__(self,key,value):
if key == 'color' or key == 'age' or key == 'my_dict': # want to make like this 'self.__dict__.keys()'
object.__setattr__(self,value)
else:
print('Wrong value')
主要思想是禁止用户向类添加新的自定义属性。
是否有办法告诉__setattr__
是否从__init__
调用了密钥?
如果是这样,那么我可以在self.__dict__.keys()
中使用__setattr__
,而不必按名称检查每个键
解决方法
使用__slots__
类属性:
class Toy:
__slots__ = ('color','age','my_dict')
def __init__(self,color,age):
self.color = color
self.age = age
self.my_dict = {
'name':'Yoyo','has_pets': False,}
任何尝试分配给color
,age
或my_dict
以外的属性的尝试都会导致AttributeError
。
没有发现比这更好的
class Toy:
_keys = ["color","age","my_dict"]
def __init__(self,age):
self.color = color
self.age = age
self.my_dict = {
'name':'Yoyo',}
def __setattr__(self,key,value):
if key in self._keys:
object.__setattr__(self,value)
else:
print('Wrong value')