本文介绍了Python 在类中有“私有"变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自 Java 世界,正在阅读 Bruce Eckels 的 Python 3 模式、食谱和习语.

I'm coming from the Java world and reading Bruce Eckels' Python 3 Patterns, Recipes and Idioms.

在阅读类时,它继续说在 Python 中不需要声明实例变量.您只需在构造函数中使用它们,然后繁荣,它们就在那里.

While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and boom, they are there.

例如:

class Simple:
    def __init__(self, s):
        print("inside the simple constructor")
        self.s = s

    def show(self):
        print(self.s)

    def showMsg(self, msg):
        print(msg + ':', self.show())

如果这是真的,那么 Simple 类的任何对象都可以在类之外更改变量 s 的值.

If that’s true, then any object of class Simple can just change the value of variable s outside of the class.

例如:

if __name__ == "__main__":
    x = Simple("constructor argument")
    x.s = "test15" # this changes the value
    x.show()
    x.showMsg("A message")

在 Java 中,我们学习了公共/私有/保护变量.这些关键字是有道理的,因为有时您希望类中的变量是该类之外的任何人都无法访问的.

In Java, we have been taught about public/private/protected variables. Those keywords make sense because at times you want variables in a class to which no one outside the class has access to.

为什么在 Python 中不需要?

Why is that not required in Python?

推荐答案

这是文化.在 Python 中,您不会写入其他类的实例或类变量.在 Java 中,如果您真的愿意,没有什么可以阻止您做同样的事情 - 毕竟,您始终可以编辑类本身的源代码以达到相同的效果.Python 摒弃了这种伪装的安全性,并鼓励程序员承担责任.在实践中,这非常有效.

It's cultural. In Python, you don't write to other classes' instance or class variables. In Java, nothing prevents you from doing the same if you really want to - after all, you can always edit the source of the class itself to achieve the same effect. Python drops that pretence of security and encourages programmers to be responsible. In practice, this works very nicely.

如果您出于某种原因想模拟私有变量,您始终可以使用 .Python 修改了诸如 __foo 之类的变量的名称,这样它们就不容易被包含它们的类之外的代码看到(尽管如果你确定的话,你可以绕过它足够了,就像您可以绕过 Java 的保护一样,如果您使用它).

If you want to emulate private variables for some reason, you can always use the __ prefix from PEP 8. Python mangles the names of variables like __foo so that they're not easily visible to code outside the class that contains them (although you can get around it if you're determined enough, just like you can get around Java's protections if you work at it).

按照同样的约定,_ 前缀意味着即使技术上没有阻止您这样做.您不会使用看起来像 __foo_bar 的另一个类的变量.

By the same convention, the _ prefix means stay away even if you're not technically prevented from doing so. You don't play around with another class's variables that look like __foo or _bar.

这篇关于Python 在类中有“私有"变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:04