簡體   English   中英

如何將字典的值設置為對另一個字典的值的引用?

[英]How do I set a value of a dictionary to a reference to a value of another dictionary?

對於我正在制作的游戲,我想創建一個對象,該對象的屬性可以設置為另一個對象的屬性(例如,door.locked = lock.locked)。 當我更新第二個對象的屬性(在本例中為lock )時,第一個對象( door )的相應屬性也應更新。 這樣,解鎖鎖也將解鎖門。 我目前使用字典來實現此功能,如下所示:

class Lock():
    def __init___(self, locked = True):
        self.attributes = {'locked': locked}

    def toggleLock():
        self.attributes.update({'locked': not self.attributes['locked']})

class Door():
    def __init__(self, locked = False):
        self.attributes = {'locked': locked}

然后,我應該能夠做到這一點:

>>>lock1 = Lock(locked = True)
>>>door1 = Door(locked = lock1.attributes['locked'])
>>>
>>>lock1.attributes['locked']
True
>>>door1.attributes['locked']
True
>>>
>>>lock1.toggleLock()
>>>lock1.attributes['locked']
False
>>>door1.attributes['locked']
False

但是,當我調用toggleLock()方法時,鎖的狀態會更改,而門的狀態不會更改。 字典是可變的,所以在lock1的情況下door1的字典不應該更新嗎?
我將如何實施它以使其起作用?

在您的代碼中,您實際上並沒有共享同一本字典,而是在Door的構造函數中創建了一個新字典,請嘗試執行以下操作:

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

順便說一句,在特定情況下,您親自提交給我,我將使Lock成為Door的成員,並通過@property共享屬性,並使getter嘗試從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)

用法示例:

>>>l=Lock()
>>>d=Door(l)
>>>d.locked
True
>>>l.toggleLock()
>>>d.locked
False
>>>d.attributes
{'color': 'Blue', 'locked': False}

做到這一點的一種可能方法(至少是我喜歡的方法)是定義一個Singleton 請注意,這對python 2.x有效,我不知道它是否在python 3.x中有效

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args)  # , **kwargs
        return cls._instances[cls]

然后將其元類化為您的鎖類

class Lock():
    __metaclass__ = Singleton

    def __init___(self, locked = True):
        self.attributes = {'locked': locked}

    def toggleLock():
        self.attributes.update({'locked': not self.attributes['locked']})

簡單來說, Singleton僅允許您創建該對象的一個​​實例。 第一次調用將創建一個新對象,之后的調用將不會創建一個新對象,但會返回您通過第一次調用創建的舊對象。

door_1_status = Lock()  # will create a Lock object
door_2_status = Lock()  # will not crate a new Lock, but return the already created Lock object.

因此,從Lock類創建的所有鎖都將共享同一對象,從而具有相同的狀態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM