+ 10

Can you write code to determine the name of an object in Python?

4th Feb 2020, 6:36 PM
SHADOW 🌀
SHADOW 🌀 - avatar
8 Respostas
+ 4
There was an interesting discussion about this a while ago... I hoped I found the right one. https://www.sololearn.com/discuss/1604705/?ref=app
4th Feb 2020, 6:39 PM
HonFu
HonFu - avatar
+ 3
So No objects in Python have any associated names. So there is no way of getting the one for an object. The assignment is only the means of binding a name to the value. The name then can only refer to access the value. The most we can do is to find the reference name of the object
4th Feb 2020, 6:43 PM
SHADOW 🌀
SHADOW 🌀 - avatar
+ 2
I found a few other discussions about this topic, using the search bar, so your question may be a duplicate. I quickly want to add, that generally you don't need to get and use the variable's name in the code. Maybe you want to tell us, what you really want to do? There may be an easier way. https://www.sololearn.com/discuss/1704493/?ref=app https://www.sololearn.com/discuss/2152620/?ref=app
4th Feb 2020, 6:45 PM
HonFu
HonFu - avatar
+ 2
Here is my example is it correct class Test: def __init__(self, name): self.cards = [] self.name = name def __str__(self): return '{} holds ...'.format(self.name) obj1 = Test('obj1') print obj1 obj2 = Test('obj2') print obj2
4th Feb 2020, 6:51 PM
SHADOW 🌀
SHADOW 🌀 - avatar
+ 2
Second one nice globals demonstration. 👍 BUT try this: def VarName(var): search=globals() for item in search: if(search[item]==var): return item a=20 b=[2,80] c=[2,80] print(VarName(a)) print(VarName(c)) Your method only works if a value exists only once.
4th Feb 2020, 7:04 PM
HonFu
HonFu - avatar
+ 1
Please, if you post code, write it in a way that it actually runs, so that people who test it to answer don't have to fix all the indentations first. You can also save it in Code Playground and link it here. I have changed your code a bit. class Test: def __init__(self, name): self.cards = [] self.name = name def __str__(self): return '{} holds ...'.format(self.name) obj1 = Test('Willy') print(obj1) obj2 = Test('Betty') print(obj2) See what I did? I gave the objects different names to their variable names. If this is all you want to do, making an object return a stored value if you print it, yeah, you can use __str__ or __repr__. That's not the same as getting the name your object had in the code, you're just accessing an attribute.
4th Feb 2020, 7:00 PM
HonFu
HonFu - avatar