私有变量在python类中的实际实现 [英] Actual implementation of private variables in python class

查看:109
本文介绍了私有变量在python类中的实际实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Python中对象名称前的单下划线和双下划线的含义


我有一个问题,当我阅读python文档中的私有变量链接



 <$ c $ 

c>>>>> class a():
def __init __(self):
self.public = 11
self._priv = 12
>>> b = a()
>>>> print b._priv
>>>> 12

我想知道是否有一种方法可以使变量

解决方案


  • Guido van Rossum认为: em>。

  • 扩展版本:我们都是成年人。



您可以隐藏 em>如果你必须,但你真的shoudn't:

  class NonAdult(object):
def __init __ self):
self .__ private_number ='42'
def __getattr __(self,name):
如果name.startswith('__ private'):
raise AttributeError

如果__name__ =='__main__':
na = NonAdult()
print(na .__ private_number)#raisees AttributeError
print(na .__ dict __ ['_ NonAdult__private_number'])仍然会返回42


Possible Duplicate:
The meaning of a single- and a double-underscore before an object name in Python

I had a question when I was reading the python documentation on private variables link.

So the documentation tells that it is a convention to name private variables with an underscore but python does not make the field private.

>>> class a():
      def __init__(self):
         self.public = 11
         self._priv = 12
>>> b = a()
>>> print b._priv
>>> 12

I wanted to know if there is a way in which I can make a variable "truly" private in python.

解决方案

  • Guido van Rossum put it: we are all adults.
  • The extended version: We are all adults. Feel free to shoot yourself in the foot if you must.

You can hide it a bit if you must, but you really shoudn't:

class NonAdult(object):
    def __init__(self):
        self.__private_number = '42'
    def __getattr__(self, name):
        if name.startswith('__private'):
            raise AttributeError

if __name__ == '__main__':
    na = NonAdult()
    print(na.__private_number) # raises AttributeError
    print(na.__dict__['_NonAdult__private_number']) # would still return 42

这篇关于私有变量在python类中的实际实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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