且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Python中的self方法获取自我对象名称

更新时间:2021-07-31 03:52:11

正如你对你的问题的评论所说的,这是不可能的,考虑以下方法的代码:

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 ...