我们可以在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: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'

实例变量没有作用域,它们是特定对象的属性。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()

最新更新