How to pass object to a function in this scenario
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.
精彩评论