如何从类访问Python模块的私有变量 [英] How to access private variable of Python module from class

查看:254
本文介绍了如何从类访问Python模块的私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3中,为类变量加上前缀会使我在修改类内的名称时成为私有变量.如何访问类中的模块变量?

In Python 3, prefixing a class variable makes it private my mangling the name within the class. How do I access a module variable within a class?

例如,以下两种方法不起作用:

For example, the following two ways do not work:

__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存在未修改的位置:

Running locals() shows that the variable __a exists unmangled:

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

[添加了换行符以提高可读性]

[Newlines added for legibility]

在模块(与解释器相对)中运行相同的代码将导致完全相同的行为.使用Anaconda的Python 3.5.1 :: Continuum Analytics, Inc..

Running same code in a module (as opposed to interpreter) results in the exact same behavior. Using Anaconda's Python 3.5.1 :: Continuum Analytics, Inc..

推荐答案

这很丑陋,但您可以访问全局变量:

It's ugly but You could access globals:

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

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

You can also put it in a dict:

__a = 3

d = {"__a": __a}

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

或列表,元组等.和索引:

Or a list, tuple etc.. and index:

__a = 3

l = [__a]

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

这篇关于如何从类访问Python模块的私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆