相关疑难解决方法(0)

Python在类中有"私有"变量吗?

我来自Java世界并阅读Bruce Eckels的Python 3模式,食谱和成语.

在阅读类时,接着说在Python中没有必要声明实例变量.你只需在构造函数中使用它们,然后繁荣,它们就在那里.

例如:

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())
Run Code Online (Sandbox Code Playgroud)

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

例如:

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

在Java中,我们学习了有关公共/私有/受保护变量的知识.这些关键字是有意义的,因为有时你想要类中的变量,类外没有人可以访问.

为什么Python中不需要这样做?

python private class

532
推荐指数
11
解决办法
42万
查看次数

标签 统计

class ×1

private ×1

python ×1