首页 > 解决方案 > 我们可以在内部类中使用外部类的实例变量,还是在 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()

在这里,我在 showAddress() 方法中的 self.name 处遇到错误

我们可以在内部访问外部块的实例变量,反之亦然吗?

错误如下,我使用的是 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'

标签: pythonoop

解决方案


实例变量没有作用域,它们是特定对象的属性。该Address对象与Students创建它的对象不同,因此不能用于self引用创建者对象。

您可以将 传递StudentsAddress构造函数,并将其保存以供将来参考。

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

推荐阅读