我来自Java世界,正在阅读布鲁斯·埃克尔斯(Bruce Eckels)的"Python 3 Patterns, Recipes and Idioms".
在阅读有关类的内容时,它接着说,在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())
如果这是真的,那么类Simple
的任何对象都可以在类之外更改变量s
的值.
例如:
if __name__ == "__main__":
x = Simple("constructor argument")
x.s = "test15" # this changes the value
x.show()
x.showMsg("A message")
在Java中,我们学习了公共/私有/受保护变量.这些关键字是有意义的,因为有时你需要一个类中的变量,而这个类之外的任何人都无权访问它.
为什么Python中不需要这样做?