ringa_lee2017-05-18 10:54:40
parent.name在parent实例化之前不存在,所以child没法访问到parent.name
有两种方法
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()
或者先实例化parent然后传参进去
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()