如何实现一个类的属性设置?

2024-05-23 17:53:35 发布

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

我的课程

class Base:
    #has no attributes of its own

    def __init__(self, params):
        for key in params:
            if hasattr(self, key):
                self[key] = params[key]

    def __setitem__(self, key, value):
        self[key] = value



class Child(Base):
    prop1 = None
    prop2 = None

然而,当self[key] = value递归调用self.__setitem__时,这将进入无休止的递归

我的目标是能够像这样将字典传递到Child()构造函数中

^{pr2}$

像Child这样的类有很多,但是有不同的字段。params是来自json blob的dict。我想使用Base作为不同类的泛型填充器,比如Child

我见过使用内部dict来完成我所要求的内容的方法,但据我所知(我对Python是全新的)这将阻止通过点表示法访问方法(我宁愿避免)。在


Tags: 方法keynoselfnonechildbasevalue
2条回答

我能想象的最接近您想要的是使用setattr,它接受一个对象、一个属性名(作为str)和该属性的值。在

class Base(object):
    def __init__(self, params):
        for k, v in params.iteritems():
            if hasattr(self, k):
                setattr(self, k, v)

class Child(Base):
    def __init__(self, params):
        self.field1 = None  # create attributes here, not at class level
        self.field2 = None
        Base.__init__(self, params)

params = dict(
    field1 = "one",
    field2 = "two",
    field3 = "tree", # ignored when used with Child since it has no field3
)
c = Child(params)

只需更新__init__中实例的__dict__

class Base:
    def __init__(self, params):
        for key in params:
            if hasattr(type(self), key):
                self.__dict__[key] = params[key]

然后:

^{pr2}$

孙子们会表现得:

class GrandChild(Child):
    field3 = None

gc = GrandChild(dict(field1="one", field2="two", field3="three"))

print(gc.field1)     # "one"
print(gc.field2)     # "two"
print(gc.field3)     # "three"

相关问题 更多 >