问题
I am trying to find a way to automatically print the object reference name with just a print object
To be more specific.
Lets say I have a class:
class A:
def __init__(self):
self.cards = []
def __str__(self):
# return a string representation of A
return "A contains " ...
...
Now whenever i create an object
test = A()
and I use the print test
it will get something like (do not mind the dots)
A contains ...
What I want to achieve is to automatically print the object reference name instead of the class name:
test contains ...
The self.__class__
or self.__name__
wont work since it returns a weird string like <class '__main__.A'>
.
How should __str__
be implemented to achieve this?
Thanks in advance.
回答1:
As the comments on your question have stated, it is not possible and also unwise, consider something along the lines of the following approach instead:
class A:
def __init__(self, name):
self.cards = []
self.name = name
def __str__(self):
return '{} contains ...'.format(self.name)
>>> test = A('test')
>>> print test
test contains ...
>>> a = A('hello')
>>> print a
hello contains ...
来源:https://stackoverflow.com/questions/23580236/how-to-get-self-object-name-from-self-method-in-python