简体   繁体   English

使用基类分配子类属性时出现Python类继承问题

[英]Python class inheritance issue occurs when using base class to assign attributes of subclass

When using base class to create sub class attribute, I got an error that sub class has no member which I created in the base class method.当使用基类创建子类属性时,我收到一个错误,即子类没有我在基类方法中创建的成员。 Codes are shown below代码如下所示

class Base(object):
    def setAttributes(self, data):
        for key in data:
            self.key = data[key]

class Sub(Base):
    pass

data = {'id':1, 'name': 'Name'}
a = Sub()
Base.setAttributes(a, data)

print(a.id)

And the error messages are : AttributeError: 'Sub' object has no attribute 'id'.错误消息是: AttributeError: 'Sub' object has no attribute 'id'。

Is there any solution to use base class to assign sub class attributes in python?有没有什么解决方案可以使用基类在python中分配子类属性?

This has nothing to do with inheritance.这与继承无关。 You have assigned the value to a.key not a.id .您已将该值分配给a.key而不是a.id In fact you have assigned all your values to a.key .事实上,您已将所有值分配给a.key

I believe you want setattr(self, key, data[key]) in place of self.key = data[key] .我相信你想要setattr(self, key, data[key])代替self.key = data[key] Or just do away with the loop entirely and do self.__dict__.update(data) .或者只是完全取消循环并执行self.__dict__.update(data)

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

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