概述
class Car(object):
def __init__(self, color, engine, oil):
self.color = color
self.__engine = engine
self.__oil = oil
a = Car('black', 'a cool engine', 'some cool oil')
We assume that __engine and __oil variables are private which means I cannot access them through a call like a.__engine. However, I can use __dict__ variable to access and even change those variables.
# Accessing
a.__dict__
{'_Car__engine': 'a cool engine', 'color': 'black', '_Car__oil': 'some cool oil'}
# Changing
a.__dict__['_Car__engine'] = "yet another cool engine"
a.__dict__
{'_Car__engine': 'yet another cool engine', 'color': 'black', '_Car__oil': 'some cool oil'}
The problem is simple. I want private variables to be accessed and changed only inside the class.
解决方案
What you are trying to do is not possible in Python.
“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python.
最后
以上就是任性衬衫为你收集整理的python私有变量_如何使Python无法访问私有变量?的全部内容,希望文章能够帮你解决python私有变量_如何使Python无法访问私有变量?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复