search

Home  >  Q&A  >  body text

How to access the parent class in python class nesting

#!/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()
淡淡烟草味淡淡烟草味2757 days ago886

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-05-18 10:54:40

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

    reply
    0
  • Cancelreply