我有一个类,它有很多属性。我想用从yaml文件解析的dict覆盖任意数量的dict。我尝试了几种方法,包括__getattributes__
和使用新变量设置实例__dict__
yaml看起来像
property_a: 1
property_b: 2
我用__getattribute__
尝试的第一种方法会导致递归错误,因为我试图一次又一次地访问self.yamlsettings
import yaml
class Properties(object):
def __init__(self):
with open("config/staging/kjh.yaml") as f:
yamlsettings = yaml.load(f)
self.yamlsettings = yamlsettings
def __getattribute__(self, attr):
try:
return self.yamlsettings[attr]
except KeyError:
return object.__getattribute__(self, attr)
@property
def property_a(self):
return "a"
@property
def property_b(self):
return "b"
@property
def property_c(self):
return "c"
我尝试的第二种方法是将实例的dict设置为yaml文件中的键值对
问题是为什么我试图访问它调用属性而不是属性的属性
import yaml
class Properties(object):
def __init__(self):
with open("config/staging/kjh.yaml") as f:
yamlsettings = yaml.load(f)
for k, v in yamlsettings.items():
self.__dict__[k] = v
@property
def property_a(self):
return "a"
@property
def property_b(self):
return "b"
@property
def property_c(self):
return "c"
prop = Properties()
prop.__dict__
>> {'property_a': 1, 'property_b': 2}
prop.property_a
>> 'a'
谁能给我指出正确的方向吗?我想我可能可以通过getter实现这一点,但它看起来非常冗长,因为我有很多属性
谢谢
要避免递归错误,请使用超类(
object
)方法访问self.yamlsettings
:相关问题 更多 >
编程相关推荐