Python在类中有“私有”变量吗? [英] Does Python have “private” variables in classes?

查看:436
本文介绍了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__(self1, str):
        print("inside the simple constructor")
        self1.s = str
    def show(self1):
        print(self1.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中,我们已经讲授了public / private / protected变量。这些关键字是有意义的,因为有时你想要一个类中没有人可以访问的类中的变量。

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.

如果你想因某些原因模拟私有变量,你总是可以使用 __ 前缀从 PEP 8 。 Python破坏了 __ foo 这样的变量的名称,使得它们对包含它们的类之外的代码不容易看到(尽管你可以

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

按照相同的约定,如果你已经确定足够了,就像你可以实现Java的保护) _ 前缀表示即使在技术上无法阻止此操作,也应保持不变。你不会使用类似 __ 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在类中有“私有”变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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