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

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

本文介绍了如何从Python中的self方法获取自我对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法来自动打印对象引用名称只需一个打印对象
更具体。
假设我有一个类:

I am trying to find a way to automatically print the object reference name with just a print objectTo 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()

code> print test 它会得到类似的东西(不介意点)

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

self .__ class __ self .__ name __ 一个奇怪的字符串,如< class'__main __。A'>

The self.__class__ or self.__name__ wont work since it returns a weird string like <class '__main__.A'>.

> __ str __ 实现这个?
提前感谢。

How should __str__ be implemented to achieve this?Thanks in advance.

推荐答案

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

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

这篇关于如何从Python中的self方法获取自我对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:43