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