我试图访问另一个函数中声明的变量,但是
ERROR:
AttributeError: 'Myclass1' object has no attribute 'myDictIn'
我使用的代码如下:
class Myclass1(object):
def __init__(self):
pass
def myadd(self):
x=self.myDictIn # tried accessing variable declared in another function
return x
def mydict(self): #variable declared in this function
myDictIn={1:[1,2,3,4],3:[4,5,6,7]}
self.myDictIn= myDictIn
return myDictIn
inst=Myclass1() # Created instance
inst.myadd() # Accessing function where I am using an variable declared in another function
我也试着宣布它是全球性的
def mydict(self): #variable declared in this function
global myDictIn
myDictIn={1:[1,2,3,4],3:[4,5,6,7]}
self.myDictIn= myDictIn
return myDictIn
但还是有同样的错误
请帮帮我。。。。 实际上,我需要访问一个函数中生成的变量,并在另一个函数中使用它 我试过。。。。。你知道吗
所以我必须能够访问在一个函数中生成的变量,并在另一个函数中使用它。请帮我找到答案
您的实例从不调用mydict方法。记住python是逐行解释的自体myDictIn在那一点上不会被分配。你知道吗
相反,你为什么不写信呢self.myDictIn=.... 在构造函数中?你知道吗
在myadd(self)中,将myDictIn声明为global。如您所知,变量在使用之前需要声明/赋值。如果程序在分配之前遇到myDictIn,则抛出错误。所以请在程序遇到myDictIn之前声明myDictIn。你知道吗
希望这有帮助!你知道吗
看起来您只需要一个} 来完成:
getter
和setter
在这里,您可以使用python ^{这样,仍然可以轻松地更改
MyDictIn
的值相关问题 更多 >
编程相关推荐