我想在這裏做一些防禦性的編程,以避免對象以不易調試的方式改變狀態,所以在Python中以下是可能的是有辦法保護Foo.name不被更改,以便強制我更明確地執行此操作?在Python中保護可變對象的變化
class A(object):
def __init__(self, foo):
self.foo = foo
class B(object):
def __init__(self, foo):
self.foo = foo
def rename(self, new_name):
self.foo.name = new_name
class Foo(object):
def __init__(self, name):
self.name = name
if __name__ == '__main__':
foo = Foo('Fooname')
print 'A foo instance is born and baptized as %s' % foo.name
ainstance = A(foo)
print 'The foo instance is then passed to A and is still called %s' % foo.name
binstance = B(foo)
print 'But then the foo instance is passed to B'
binstance.foo.name = 'Barname'
print 'And in B it is renamed to %s' % foo.name
此輸出:
A foo instance is born and baptized as Fooname
The foo instance is then passed to A and is still called Fooname
But then the foo instance is passed to B
And in B it is renamed to Barname
我知道我可以實現重命名美孚,我可以強迫自己使用的方法,或者我可以使用名稱重整但是這仍然沒有真正阻止我在不經意間改變foo.name
即使它被稱爲foo._name
也很難保護您免於斷開計算機並將其扔出最近的窗口。 – unwind
你提到'foo._name',那是一個下劃線前綴。這並不完美,但是您是否嘗試過使用兩個下劃線作爲前綴? 'foo .__ name' – cdarke
嗨cdarke,這是故意的。我相信這是Python世界中的一種常見做法,它具有雙下劃線的好處,而不會改變名稱並添加對類名稱的依賴關係。 – Lorenzo