簡體   English   中英

如何訪問在另一個函數中聲明的變量

[英]How to access a variable declared within another function

我正在嘗試訪問在另一個函數中聲明的變量,但是我得到了

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. 聲明為類變量(在初始化之前和聲明類名稱之后)
  2. init中聲明該變量這兩種方法會導致進一步的錯誤

因此,我必須能夠訪問在一個函數中生成的變量並在另一個函數中使用它。 請協助我找到答案

您的實例永遠不會調用方法mydict。 請記住,python是逐行解釋的,self.myDictIn不會在該點被分配。

相反,為什么不在構造函數中編寫self.myDictIn = ....?

在myadd(self)中,將myDictIn聲明為全局。 如您所知,在使用變量之前,必須先聲明/分配變量。 如果程序在分配之前遇到myDictIn,它將引發錯誤。 因此,請在程序遇到myDictIn之前聲明myDictIn。

希望這可以幫助!

看起來您只需要在這里使用gettersetter ,就可以使用python properties來做到這一點:

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]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM