如何使私有变量在Python中不可访问?[重复]

发布于 2021-01-29 16:21:55

这个问题已经在这里有了答案

Python在类中是否有“私有”变量? (12个答案)

5年前关闭。

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

我们假设__engine和__oil变量是私有的,这意味着我无法通过a .__
engine之类的调用来访问它们。但是,我可以使用__dict__变量来访问甚至更改这些变量。

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

问题很简单。我希望仅 内部 访问和更改私有变量。

关注者
0
被浏览
151
1 个回答
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看