Python parent class accessing class variable of child class

前端 未结 2 1674
盖世英雄少女心
盖世英雄少女心 2020-12-17 17:57

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 functi

相关标签:
2条回答
  • 2020-12-17 18:22

    You were close. This works:

    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__()
    

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

    0 讨论(0)
  • 2020-12-17 18:37

    Adding to the above answer,

    Although ATTR is a class variable in the child class, the instance variable of the child class is able to access the class variable ATTR because, Python does the following using namespaces

    1. Checks the namespace of the instance (self.dict) for the ATTR variable.
    2. If the above fails then it checks the namespace of its class. So it is able to get the value of the class variable although it's accessed using the instance variable.
    0 讨论(0)
提交回复
热议问题