Kernel Kernel - 1 year ago 43
Python Question

python derived class call a global variable which initialized in superclass

i tried initialized the derived class by default superclass's __init__function, then i tried to use the global variable which initialized in the init function.
but there was an error message said the variable "dr" in class One is not defined

class Base(object):
dr = None
def __init__(self, driver):
global dr
dr = driver

class One(Base):
def fun(self):

if __name__=="__main__":
driver = 1
test = One(driver)

Answer Source

You have defined dr as a class variable, a static field available to all classes, and you should see this field from all objects with Base.dr. global should not be used in methods, but rather in functions.

This class variable is not inherited and One.dr is not defined.

To be able to access dr in objects of the subclass you need to make it an instance variable. Modify your base class as

class Base(object):
    #dr = None # this will differ from self.dr even if you let it here
    def __init__(self, driver):
        self.dr = driver

You can use it in the subclass as

class One(Base):

    def __init__(self,driver): 
        super(Base, self).__init__(driver) #call constructor of superclass
    def fun(self):