开发者

How to pass object to a function in this scenario

开发者 https://www.devze.com 2023-01-21 08:07 出处:网络
I have the following piece o开发者_如何学运维f code: NameX.functionA(functionB(Dictionary[\"___\"]))

I have the following piece o开发者_如何学运维f code:

 NameX.functionA(functionB(Dictionary["___"]))

Instead of _ I would like to make a reference to NameX in the form of a string, so that the program interprets it as

 NameX.functionA(functionB(Dictionary["NameX"]))

How can I do this? I tried to use str(self), but it is clearly wrong.

Thanks


Is NameX.__name__ perhaps what you want?


You can use

Name.__name__

on an uninitialized object and

Name.__class__.__name__

on an initialized object.


Abusive but it works:

>>> def getvarname(var):
    d = globals()
    for n in d:
        if d[n] is var:
            return n
    return None

>>> class NameX: pass

>>> getvarname(NameX)
'NameX'

Works on things that aren't just classes, too:

>>> inst1 = NameX()
>>> getvarname(inst1)
'inst1'

You might be shot if this ends up in real code, though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号