Python父类访问子类的类变量 [英] Python parent class accessing class variable of child class

查看:707
本文介绍了Python父类访问子类的类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在我的Python项目中实现一些继承,并且遇到了障碍。我正在尝试创建一个baseParentClass,它将处理许多子类的基本功能。在这个具体的例子中,我试图初始化一个具有许多属性(设置为0)的实例,存储为Child中的类变量列表(称为ATTRS)。我不确定如何在父类中使用此ATTRS。

I'm currently trying to implement some inheritance in my Python project and have hit a road block. I'm trying to create a baseParentClass that will handle the basic functionality for a lot of child classes. In this specific example I am trying to initialize an instance with a number of attributes (set to 0), stored as a class variable list (called ATTRS) in the Child. I am unsure of how to use this ATTRS in the parent class.

class Parent(object):
    def __init__():
        for attr in ATTRS:
            setattr(self, attr, 0)

class Child(Parent):
    #class variable
    ATTRS = [attr1, attr2, attr3]

    def __init__():
        super(Child, self).__init__()

我可以在子节点中将ATTRS存储为self.ATTRS,然后在Parent中成功使用self.ATTRS,但我最好将它们存储为类变量。

I could store ATTRS as self.ATTRS in Child, and then use self.ATTRS in Parent successfully, but it seems preferable to me to have them stored as a class variable.

或者我可以将ATTRS作为参数传递:

Alternatively I could pass ATTRS as a parameter like so:

class Child(Parent):
    #class variable
    ATTRS = [attr1, attr2, attr3]

    def __init__():
        super(Child, self).__init__(ATTRS)

但我想知道这是否在某种程度上违背了使用继承的重点?

but I'm wondering whether this somehow defeats the point of using inheritance in the first place?

我会感激任何想法,提示或反馈我是否是酒吧完全把错误的树弄死了!

I'd be grateful for any ideas, hints or feedback whether I'm barking up the wrong tree completely!

谢谢

推荐答案

你是关。这有效:

class Parent(object):
    def __init__(self):
        for attr in self.ATTRS:
            setattr(self, attr, 0)

class Child(Parent):
    #class variable
    ATTRS = ['attr1', 'attr2', 'attr3']

    def __init__(self):
        super(Child, self).__init__()

在这里,你在类级别设置 ATTRS 列表,并在 self中方便地访问它.ATTRS 在baseclass的 __ init __

Here, you set the ATTRS list at the class level, and conveniently access it in self.ATTRS at baseclass's __init__.

这篇关于Python父类访问子类的类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆