我来自Java世界,阅读Bruce Eckels的Python 3 Patterns,Recipes和Idioms。
在阅读类时,它继续说在Python中不需要声明实例变量。你只是在建设者中使用它们,繁荣,他们在那里。
举个例子:
class Simple: def __init__(self1, str): print("inside the simple constructor") self1.s = st 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中不需要?
相似问题