我来自Java世界,正在阅读Bruce Eckels的《Python 3 Patterns, Recipes and idiom》。
在阅读有关类的内容时,会继续说在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中不需要这个?
下面是我处理Python 3类字段的方法:
class MyClass:
def __init__(self, public_read_variable, private_variable):
self.public_read_variable_ = public_read_variable
self.__private_variable = private_variable
我只在MyClass方法中使用两个下划线访问__private_variable。
我用一个下划线对public_read_variable_进行读访问
在类之外,但从不修改变量:
my_class = MyClass("public", "private")
print(my_class.public_read_variable_) # OK
my_class.public_read_variable_ = 'another value' # NOT OK, don't do that.
“在java中,我们学习了公共/私有/受保护变量”
“为什么在python中不需要这个?”
出于同样的原因,它在Java中不是必需的。
您可以自由使用或不使用private和protected。
作为Python和Java程序员,我发现私有和受保护是非常非常重要的设计概念。但实际上,在数万行Java和Python代码中,我从未真正使用过private或protected。
为什么不呢?
我的问题是"被谁保护?"
我团队中的其他程序员?他们有消息来源。当他们可以改变的时候,保护意味着什么?
其他团队的其他程序员?他们在同一家公司工作。只要打个电话,他们就能找到线人。
客户吗?这是一种雇佣式编程(通常)。客户机(通常)拥有代码。
那么,我到底在保护谁呢?