Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

oop - Can we use instance variable of outer class in inner class or vice in Inner class concept in Python?

class Students:
    def __init__(self,name,rollno,houseNo,area):
        self.name=name
        self.rollno=rollno
        self.address=self.Address(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,houseNo,area):
            print('Student's Address')
            self.houseNo =houseNo
            self.area=area
        def showAddress(self):
            print("My name is "+ self.name+' and address: '+self.area)
    
object1 = Students('Anubhav',18,'B-24','Lucknow')
object1.address.showAddress()

Here I got error at self.name in showAddress() method

Can we access instance variable of outer block in inner and vice-versa ?

The Error is as follow, I am using Python3

Student's Address
Anubhav and 18
Traceback (most recent call last):
  File "C:UsersFostersFCDesktopdelete.py", line 21, in <module>
    a.showAddress()
  File "C:UsersFostersFCDesktopdelete.py", line 17, in showAddress
    print("My name is "+ self.name+' and address: '+self.area)
AttributeError: 'Address' object has no attribute 'name'
question from:https://stackoverflow.com/questions/65905569/can-we-use-instance-variable-of-outer-class-in-inner-class-or-vice-in-inner-clas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...