,你真的不共享相同的字典,您可以創建在門的構造一個新的,嘗試做:
class Door():
def __init__(self, attributes):
self.attributes = attributes
然後再去做這樣稱呼它:
>>>lock1 = Lock(locked = True)
>>>door1 = Door(lock1.attributes)
編輯:
如果你想有不同的字典,只有共享的價值觀,那麼你可能想包裝在一個類中的值,然後共享它的一個實例:
class SharedValue(object):
def __init__(self, val):
self.value = val
class Lock():
def __init___(self, locked = True):
self.attributes = {'locked': SharedValue(locked)}
def toggleLock():
self.attributes['locked'].value = not self.attributes['locked'].value
class Door():
def __init__(self, locked = False):
if not isinstance(locked, SharedValue):
locked = SharedValue(locked)
self.attributes = {'locked': locked}
,那麼你可以創建像你想要的,但使用值的代碼必須改變
>>>lock1 = Lock(locked = True)
>>>door1 = Door(locked = lock1.attributes['locked'])
>>>
>>>lock1.attributes['locked'].value
True
>>>door1.attributes['locked'].value
True
順便說一句,在你提出我個人會作出鎖門的成員的具體情況,並通過@property 共享屬性,並取得了吸氣,儘量從self.attributes
得到它,如果它不包含關鍵,從self.lock.attribute
EDIT2得到它:
添加例如,對於不同勢的解決方案:
class Lock():
def __init__(self, locked = True):
self.attributes = {'locked': locked}
def toggleLock(self):
self.attributes.update({'locked': not self.attributes['locked']})
class Door():
def __init__(self, lock_object):
self._attributes = {'color':'Blue'}
self.lock = lock_object
def get_attribute(self,key):
if key in self._attributes:
return self._attributes[key]
elif key in self.lock.attributes:
return self.lock.attributes[key]
raise KeyError(key)
@property
def attributes(self):
"""
Door's attributes
"""
# return a new dict that contains the keys of itself, and lock (and possibly more objects)
a = {}
a.update(self.lock.attributes)
a.update(self._attributes)
return a
def __getattr__(self, key):
#nice addition, makes you able to do things like `if Door.locked:`
return self.get_attribute(key)
使用例子:這樣做(至少是我喜歡)被定義Singleton
的
>>>l=Lock()
>>>d=Door(l)
>>>d.locked
True
>>>l.toggleLock()
>>>d.locked
False
>>>d.attributes
{'color': 'Blue', 'locked': False}
它們是兩個完全獨立的對象,彼此之間沒有引用。一個更新會如何影響另一個呢?在這兩個字典中由'self.attributes'命名的字典是兩個完全不同的字典。 – dursk