简体   繁体   English

Python 3使用属性覆盖类方法

[英]Python 3 Overriding class method with attribute

I have a class with a bunch of properties. 我有一类带有很多属性的类。 I want to override an arbitrary number of them with a dict parsed from a yaml file. 我想用从yaml文件解析的字典来覆盖任意数量的它们。 I've tried a few approaches inculding __getattributes__ and setting the instance __dict__ with the new variable. 我尝试了几种方法,其中包括__getattributes__并将实例__dict__设置为新变量。

The yaml would look like yaml看起来像

property_a: 1
property_b: 2

The first approach I tried with __getattribute__ results in a recursion error because I'm trying to access self.yamlsettings over and over again 我尝试使用__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"

The second approach I tried was setting the instance's dict to the key value pair in the yaml file. 我尝试的第二种方法是将实例的dict设置为yaml文件中的键值对。

The problem is why I'm trying to access the attribute it calls the property rather than the attribute. 问题是为什么我要访问它调用属性而不是属性的属性。

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'

Can anyone point me in the right direction? 谁能指出我正确的方向? I think I might be able to achieve this through a getter but it seems extremely verbose because I have so many properties. 我认为我可能可以通过吸气剂实现这一目标,但是由于我有很多特性,它似乎非常冗长。

Thanks! 谢谢!

To avoid the recursion error, use the superclass ( object ) method to access self.yamlsettings : 为了避免递归错误,请使用超类( object )方法访问self.yamlsettings

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM