Instance variables are not scoped, they're attributes of specific objects. The Address
object is not the same as the Students
object that created it, so you can't use self
to refer to the creator object.
You can pass the Students
to the Address
constructor, and save that for future references.
class Students:
def __init__(self,name,rollno,houseNo,area):
self.name=name
self.rollno=rollno
self.address=self.Address(self,houseNo,area)
print(self.name ,'and',self.rollno)
def show(self):
print("My name is "+ self.name+" and rollno is" ,self.rollno)
class Address:
def __init__(self,student,houseNo,area):
print('Student's Address')
self.houseNo =houseNo
self.area=area
self.student = student
def showAddress(self):
print("My name is "+ self.student.name+' and address: '+self.area)
object1 = Students('Anubhav',18,'B-24','Lucknow')
object1.address.showAddress()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…