,你真的不共享相同的字典,您可以创建在门的构造一个新的,尝试做:
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