1

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

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()
Kernel
  • 661
  • 7
  • 10

3 Answers3

2

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):
        print(self.dr)
Radu Ionescu
  • 3,462
  • 5
  • 24
  • 43
  • haha, i know this can solve my problem, but i just don't want to add "self." everywhere, i am so lazy. but thanks still – Kernel Jul 01 '16 at 10:15
  • Reading the comment on the other post you should define a static method to import them from the `Base` class as simple as `dr=Base.dr` – Radu Ionescu Jul 01 '16 at 11:01
1

That's because global stands for the global scope of a module, so the global scope of base.py isn't the same global scope in one.py, thus global won't work. Here's a solution for cross-module variable sharing https://stackoverflow.com/a/142566/4472389. But just avoid this type of code.

Community
  • 1
  • 1
  • But it's still need using module name to call this variable. In my case, i want to this variable initialize once, and use in all subclass...just like it is used in superclass, don't need self. or module_name. to access – Kernel Jul 01 '16 at 10:25
1

Finally, i edit my code like this:

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

Maybe it's not very elegant, and i don't know if it is a good solution, but i can use "dr" variable in derived classes as many times as i want, and don't need the "self" to call it.

Kernel
  • 661
  • 7
  • 10