python派生类调用一个在超类中初始化的全局变量

时间:2016-07-01 09:43:30

标签: python inheritance global-variables

我尝试使用默认超类的__init__函数初始化派生类,然后我尝试使用在init函数中初始化的全局变量。 但是有一条错误消息说变量" dr"在第一课中没有定义

base.py:

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

one.py

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

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

3 个答案:

答案 0 :(得分:1)

那是因为global代表模块的全局范围,因此base.py的全局范围与one.py中的全局范围不同,因此global无法工作。这是跨模块变量共享java doc的解决方案。但是请避免使用这种类型的代码。

答案 1 :(得分:0)

您已将dr定义为类变量,这是一个可供所有类使用的静态字段,您应该在Base.dr的所有对象中看到此字段。 global不应该用在方法中,而应该用在函数中。

此类变量未被继承,并且未定义One.dr

为了能够访问子类对象中的dr,您需要将其设为实例变量。将基类修改为

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

您可以在子类中将其用作

class One(Base):

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

答案 2 :(得分:0)

最后,我编辑我的代码:

base.py:

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

one.py

class One(Base):
    def __init__(self, driver):
        super().__init__(driver)
        global dr
        dr = self.dr

    def fun(self):
        print(dr)

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

也许它不是很优雅,我不知道它是否是一个很好的解决方案,但我可以在派生类中使用“dr”变量多次,因为我想要,并且不需要“自我”来叫它。