如何访问在另一个函数中声明的变量

2024-06-02 05:40:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图访问另一个函数中声明的变量,但是

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

但还是有同样的错误

请帮帮我。。。。 实际上,我需要访问一个函数中生成的变量,并在另一个函数中使用它 我试过。。。。。你知道吗

  1. 声明为类变量(在init之前和声明类名之后)
  2. init中声明该变量 这两种方法会导致进一步的错误

所以我必须能够访问在一个函数中生成的变量,并在另一个函数中使用它。请帮我找到答案


Tags: 函数inself声明returnobjectinitdef
3条回答

您的实例从不调用mydict方法。记住python是逐行解释的自体myDictIn在那一点上不会被分配。你知道吗

相反,你为什么不写信呢self.myDictIn=.... 在构造函数中?你知道吗

在myadd(self)中,将myDictIn声明为global。如您所知,变量在使用之前需要声明/赋值。如果程序在分配之前遇到myDictIn,则抛出错误。所以请在程序遇到myDictIn之前声明myDictIn。你知道吗

希望这有帮助!你知道吗

看起来您只需要一个gettersetter在这里,您可以使用python ^{}来完成:

class Myclass1(object):
    def __init__(self, dict_value):
        self.myDictIn = dict_value

    @property
    def myDictIn(self):
      print(self.__myDictIn)
      return self.__myDictIn

    @myDictIn.setter
    def myDictIn(self, value):
        if not isinstance(value, dict):
            raise TypeError("dict_value must be a dict")
        self.__myDictIn = value

dict_value = {1: [1, 2, 3 ,4], 3: [4, 5, 6, 7]}
inst = Myclass1(dict_value)
inst.myDictIn # {1: [1, 2, 3 ,4], 3: [4, 5, 6, 7]}

这样,仍然可以轻松地更改MyDictIn的值

inst.myDictIn = {1: [1, 2, 3]}
inst.myDictIn # {1: [1, 2, 3]}

相关问题 更多 >