python类私有变量访问和修改_如何从类访问Python模块的私有变量

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()

results in:

Traceback (most recent call last):

File "", line 1, in

File "", line 3, in __init__

NameError: name '_B__a' is not defined

Using global does not help either:

__a = 3

class B:

def __init__(self):

global __a

self.a = __a

b = B()

results in:

Traceback (most recent call last):

File "", line 1, in

File "", line 4, in __init__

NameError: name '_B__a' is not defined

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

>>> locals()

{'__package__': None, '__name__': '__main__',

'__loader__': ,

'__doc__': None, '__a': 3, 'B': ,

'__builtins__': , '__spec__': None}

[Newlines added for legibility]

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值