簡體   English   中英

當__str__被覆蓋時,獲取python中對象實例的名稱?

[英]Get the name of the instance of an object in python, when __str__ overridden?

我正在創建一個簡單的容器系統,其中我的對象(一個名為GeneralWidget的類的所有子GeneralWidget )被分組在一些容器中,這些容器在另一組容器中,依此類推,直到所有對象都在一個全局容器中。 我有一個名為GeneralContainer的自定義類,在其中我必須覆蓋__str__方法來為我的容器提供一個描述名稱,所以我知道他里面存儲了什么樣的對象或容器。

我目前正在編寫另一個名為ObjectTracker類,其中存儲了我的對象的所有位置,因此當創建一個新對象時,它會在__init__方法中給出一個包含其名稱的列表,它是我層次結構中的“父”將自己添加到列表中並將其傳遞。 在某些時候,這個包含新創建的GeneralWidget實例之上的所有對象的列表將到達全局GeneralWidget (包含所有容器和小部件),它可以訪問我的main()ObjectTracker

這是我的問題的背景。 我的ObjectTracker有一個字典,其中每個“一級容器”都是一個鍵,並且這樣一個容器內的所有對象也存儲在字典中。 所以我有很多封裝的字典。

因為我不知道會有多少級別的容器,所以我需要一個動態語法,該語法與我需要傳遞的字典數量無關,直到我到達我想要的 BIG 字典中的位置。 我的ObjectRepository類中的(靜態)調用需要如下所示:

self._OBJECTREPOSITORY[firstlevelcontainer12][secondlevel8][lastlevel4] = myNewObject

firstlevelcontainer12包含secondlevel8 ,其中包含lastlevel4 ,新對象應放置在其中

但是我既不知道將如何調用容器,也不知道將有多少個容器,因此我決定使用exec()並組合一個包含所有名稱的字符串。 我將在這里發布我的實際代碼, ObjectTracker的定義:

class ObjectTracker:
    def __init__(self):
        self._NAMEREPOSITORY = {}

    def addItem(self, pathAsList):
        usableList = list(reversed(pathAsList))
        string = "self._NAMEREPOSITORY"
        for thing in usableList:
            if usableList[-1] != [thing]:
                string += "[" + str(thing) + "]"
            else:
                string += "] = " + str(thing)
        print(string)
        exec(string)                

問題是我已經覆蓋了GeneralContainerGeneralWidget類的__str__方法來返回一個描述名稱。 這在很多情況下都非常方便,但現在它已成為一個大問題。 上面的代碼僅在自定義名稱與對象實例的名稱相同時才有效(當然,我明白為什么!)

問題是:是否存在內置函數來執行以下操作:

>>> alis = ExampoleClass()
>>> DOESTHISEXIST(alis)
'alis'

如果不是,我怎樣才能在不破壞我正常工作的命名系統的情況下編寫自定義的?

注意:由於我不確定你想要什么,我會嘗試提供一個通用的解決方案。

首先,避免像黑瘟疫一樣使用eval/exec 使用它們時會遇到嚴重的問題,而且幾乎總有更好的方法。 這是我在下面建議的方式:

您似乎想要一種在給定特定鍵列表的嵌套字典中找到某個點的方法。 這可以很容易地使用 for 循環並遞歸遍歷所述字典來完成。 例如:

>>> def get_value(dictionary, keys):
        value = dictionary
        for key in keys:
            value = value[key]
        return value

>>> d = {'a': 1, 'b': {'c': 2, 'd': 3, 'e': {'f': 4, }, 'g': 5}}
>>> get_value(d, ('b', 'e', 'f'))
4
>>> 

如果您需要分配給某個嵌套字典的特定部分,也可以使用上面的代碼來完成:

>>> dd = get_value(d, ('b', 'e')) # grab a dictionary object
>>> dd
{'f': 4}
>>> dd['h'] = 6
>>> # the d dictionary is changed.
>>> d
{'a': 1, 'b': {'c': 2, 'd': 3, 'e': {'f': 4, 'h': 6}, 'g': 5}}
>>> 

下面是上述函數的正式版本,帶有錯誤測試和文檔(以自定義樣式):

NO_VALUE = object()


def traverse_mapping(mapping, keys, default=NO_VALUE):
    """
    Description
    -----------
    Given a - often nested - mapping structure and a list of keys, use the
    keys to recursively traverse the given dictionary and retrieve a certian
    keys value.

    If the function reaches a point where the mapping can no longer be
    traversed (i.e. the current value retrieved from the current mapping
    structure is its self not a mapping type) or a given key is found to
    be non-existent, a default value can be provided to return. If no
    default value is given, exceptions will be allowed to raise as normal
    (a TypeError or KeyError respectively.)

    Examples (In the form of a Python IDLE session)
    -----------------------------------------------
    >>> d = {'a': 1, 'b': {'c': 2, 'd': 3, 'e': {'f': 4, }, 'g': 5}}
    >>> traverse_mapping(d, ('b', 'e', 'f'))
    4
    >>> inner_d = traverse_mapping(d, ('b', 'e'))
    >>> inner_d
    {'f': 4}
    >>> inner_d['h'] = 6
    >>> d
    {'a': 1, 'b': {'c': 2, 'd': 3, 'e': {'f': 4, 'h': 6}, 'g': 5}}
    >>> traverse_mapping(d, ('b', 'e', 'x'))
    Traceback (most recent call last):
      File "<pyshell#14>", line 1, in <module>
        traverse_mapping(d, ('b', 'e', 'x'))
      File "C:\Users\Christian\Desktop\langtons_ant.py", line 33, in traverse_mapping
        value = value[key]
    KeyError: 'x'
    >>> traverse_mapping(d, ('b', 'e', 'x'), default=0)
    0
    >>>

    Parameters
    ----------
    - mapping : mapping
        Any map-like structure which supports key-value lookup.

    - keys : iterable
        An iterable of keys to be using in traversing the given mapping.
    """
    value = mapping
    for key in keys:
        try:
            value = value[key]
        except (TypeError, KeyError):
            if default is not NO_VALUE:
                return default
            raise
    return value

我想你可能正在尋找vars()

a = 5
# prints the value of a
print(vars()['a'])
# prints all the currently defined variables
print(vars())
# this will throw an error since b is not defined
print(vars()['b'])

暫無
暫無

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

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