簡體   English   中英

如何從類訪問Python模塊的私有變量

[英]How to access private variable of Python module from class

在Python 3中,為類變量加上前綴會使我在修改類內的名稱時成為私有變量。 如何訪問類中的模塊變量?

例如,以下兩種方法不起作用:

__a = 3
class B:
    def __init__(self):
        self.a = __a
b = B()

結果是:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
NameError: name '_B__a' is not defined

使用global沒有幫助:

__a = 3
class B:
    def __init__(self):
        global __a
        self.a = __a
b = B()

結果是:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
NameError: name '_B__a' is not defined

運行locals()顯示變量__a存在無__a

>>> locals()
{'__package__': None, '__name__': '__main__',
 '__loader__': <class '_frozen_importlib.BuiltinImporter'>,
 '__doc__': None, '__a': 3, 'B': <class '__main__.B'>,
 '__builtins__': <module 'builtins' (built-in)>, '__spec__': None}

[增加了換行符以提高可讀性]

在模塊(與解釋器相對)中運行相同的代碼將導致完全相同的行為。 使用Anaconda的Python 3.5.1 :: Continuum Analytics, Inc. .。

這很丑陋,但您可以訪問全局變量:

__a = 3
class B:
    def __init__(self):
        self.a = globals()["__a"]
b = B()

您也可以將其放在字典中:

__a = 3

d = {"__a": __a}

class B:
    def __init__(self):
        self.a = d["__a"]
b = B()

或列表,元組等。和索引:

__a = 3

l = [__a]

class B:
    def __init__(self):
        self.a = l[0]
b = B()

顯然,“正式”的答案是不要在課堂外使用雙下划線。 此處的文檔中暗含了這一點: https : //docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references 此外,以下(失敗的) 錯誤報告 (和此響應 )使它明確。

您正在通過傳遞未定義的變量來實例化一個類。 將__a放在類之外將不起作用,因為類不會看到此變量。 相反,您應該做的是:

__a = 3
class B:
def __init__(self, __a):
   self.a = __a
b = B(__a)

這樣,您將在構造函數中傳遞參數進行初始化。

如果您打算按自己的意願來處理名稱,那么我將向您推薦這篇文章: http : //shahriar.svbtle.com/underscores-in-python

因此,我對您要執行的操作的解決方案如下:

class R:
    global _R__a
    _R__a = 3
    def __init__(self):
        pass

class B:    
    global _R__a    
    def __init__(self):     
        self.a = _R__a
b = B()
print b.a
#3`

這樣,您還可以更具體地了解正在調用的變量,而沒有很大的修改空間。 希望這行得通。

暫無
暫無

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

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