python - 如何在 Python 中使私有(private)变量不可访问?

标签 python class oop object private

<分区>

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 变量是私有(private)的,这意味着我不能通过像 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'}

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

最佳答案

The problem is simple. I want private variables to be accessed and changed only inside the class.

因此,不要在访问以__ 开头的变量的类之外编写代码。使用 pylint 或类似的工具来捕获这样的样式错误。

关于python - 如何在 Python 中使私有(private)变量不可访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28138734/

相关文章:

python - 带有 if 语句的主循环无法正常工作

Python HDFS : Cannot read file

c++ - C++中类与函数的模板类型推导?

c# - 不可变与可变 C#

python - 从 .npy 文件制作 pandas 数据框

python - 具有出色表格支持的 Wiki 标记语言

swift - 为什么选择结构而不是类?

python - 在 Python 中以编程方式创建算术特殊方法(又名工厂函数 HOWTO)

python - 有没有一种简单的方法来 "reload"对象的方法而不完全重新实例化它?

.net - 为什么静态类只能有静态成员?