我来自Java世界,阅读Bruce Eckels的Python 3模式,食谱和成语。
在阅读关于类的时候,它继续说在Python中没有必要声明实例变量。你只是在构造函数中使用它们,并且繁荣,他们在那里。
例如:
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 __name__ == "__main__":
x = Simple("constructor argument")
x.s = "test15" # this changes the value
x.show()
x.showMsg("A message")
在Java中,我们已经被教授关于公共/私有/保护变量。这些关键字是有意义的,因为有时你想要一个类中没有人可以访问的类中的变量。
为什么在Python中不需要它?