Python: how to refer to an instance name?

后端 未结 4 1695
北恋
北恋 2021-01-14 01:45

I\'m collecting instances using the following code:

class Hand():
    instances = []
    def __init__(self):
        Hand.instances.append(self)
        self         


        
4条回答
  •  甜味超标
    2021-01-14 02:24

    I don't know if this would solve your problem or not. I needed to get instance names in order to do clear error reporting. Everywhere I looked, folks said "variables don't have names! The name is just a pointer to the thing!"

    But it turns out that getting instance names in python is pretty straightforward. Here's how I did it:

    import gc
    def instance_names(self):
        referrers = gc.get_referrers(self)
        result = []
        dict_of_things = {}
        for item in referrers:
            if isinstance(item, dict):
                dict_of_things = item
        for k, v in dict_of_things.items():
            if v == self:
                result.append(k)
        if not result:
            result = ['unnamed instance']
        return result
    

提交回复
热议问题