简体   繁体   中英

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:\Users\FostersFC\Desktop\delete.py", line 21, in <module>
    a.showAddress()
  File "C:\Users\FostersFC\Desktop\delete.py", line 17, in showAddress
    print("My name is "+ self.name+' and address: '+self.area)
AttributeError: 'Address' object has no attribute 'name'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM