How to access the parent class in python class nesting
淡淡烟草味
淡淡烟草味 2017-05-18 10:52:40
0
1
898
#!/usr/bin/env python  

class parent:  
    def __init__(self):  
        self.name = 'parent'  
  
    def getName(self):  
        print(self.name)

    class child:
        def getName(self):
            #如何访问到父类的name值
  
  
if __name__ == '__main__':  
    child =  parent.child()  
    child.getName()
淡淡烟草味
淡淡烟草味

reply all(1)
左手右手慢动作

parent.name does not exist before parent is instantiated, so child cannot access parent.name
There are two methods

class parent:  
    name = 'parent'  
  
    def getName(self):  
        print(self.name)

    class child:
        def getName(self):
            return parent.name
  
  
if __name__ == '__main__':  
    child =  parent.child()  
    child.getName()

Or instantiate the parent first and then pass the parameters in

class parent:  
    def __init__(self):  
        self.name = 'parent'  

  
    def getName(self):  
        print(self.name)

    class child:
        def __init__(self,parent):
            self.parent = parent

        def getName(self):
            return self.parent.name
  
  
if __name__ == '__main__':  
    parent = parent()
    child =  parent.child(parent)  
    child.getName()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template