#!/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()
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()