How to get self object name from self method in Python

假如想象 提交于 2019-12-23 17:16:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!