python - 我们可以在内部类中使用外部类的实例变量,还是在 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'
解决方案
实例变量没有作用域,它们是特定对象的属性。该Address
对象与Students
创建它的对象不同,因此不能用于self
引用创建者对象。
您可以将 传递Students
给Address
构造函数,并将其保存以供将来参考。
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()
推荐阅读
- excel - 基于列表的vba复制和粘贴循环
- selenium-webdriver - Node JS:Selenium-Webdriver sendKeys到字段,插入的值不正确
- javascript - 如何通过 App 直接在 Google Play 上评价我的应用
- r - 分类尺度上 geom_point 的 position_dodge 的垂直等效项
- amcharts - AmCharts (type = stock) 自定义 zoomToIndexes(start, end) 不起作用
- c# - 错误 Microsoft.SqlServer.Management.Smo.SqlSmoObject.get_ServerVersion()'。'
- python - 如何从命令行导入我的 django 应用程序模型?
- mysql - 将每月成本除以一年中剩余的月数并将其拆分为多行
- r - 如何在循环中重复调用 R 并检索结果以在 SAS 中进一步处理
- python - Jupyter Notebook Azure 机器学习实验