Python3使用attribu重写类方法

2024-10-06 13:38:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类,它有很多属性。我想用从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实现这一点,但它看起来非常冗长,因为我有很多属性

谢谢


Tags: 文件方法selfyamlreturn属性objectdef
1条回答
网友
1楼 · 发布于 2024-10-06 13:38:56

要避免递归错误,请使用超类(object)方法访问self.yamlsettings

...
def __getatttibute__(self, attr):
    try:
        return object.__getattribute__(
            self, 'yamlsettings'
        )[attr]
    except KeyError:
        return object.__getattribute__(self, attr)

相关问题 更多 >