How to get self object name from self method in Py

2019-07-02 01:40发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-07-02 02:14

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 ...
查看更多
登录 后发表回答