有没有办法在 python 中自动生成 __str__() 实现?

Is there a way to auto generate a __str__() implementation in python?

我厌倦了为我的 classes 手动实现字符串表示,我想知道是否有 pythonic 方法可以自动执行此操作。

我想要一个涵盖 class 和 class 名称的所有属性的输出。这是一个例子:

class Foo(object):
    attribute_1 = None
    attribute_2 = None
    def __init__(self, value_1, value_2):
         self.attribute_1 = value_1
         self.attribute_2 = value_2

导致:

bar = Foo("baz", "ping")
print(str(bar)) # desired: Foo(attribute_1=baz, attribute_2=ping)

在一些 Java 项目中使用 Project Lombok @ToString 后想到了这个问题。

您可以使用 vars, dir、...:[=​​15=] 迭代实例属性

def auto_str(cls):
    def __str__(self):
        return '%s(%s)' % (
            type(self).__name__,
            ', '.join('%s=%s' % item for item in vars(self).items())
        )
    cls.__str__ = __str__
    return cls

@auto_str
class Foo(object):
    def __init__(self, value_1, value_2):
        self.attribute_1 = value_1
         self.attribute_2 = value_2

已申请:

>>> str(Foo('bar', 'ping'))
'Foo(attribute_2=ping, attribute_1=bar)'

写这篇文章是假的,真回答了。 这是相同的想法,我的在阅读方面对初学者非常友好,他的实现得更好恕我直言

class stringMe(object):
        def __str__(self):
            attributes = dir(self)
            res = self.__class__.__name__ + "("
            first = True
            for attr in attributes:
                if attr.startswith("__") and attr.endswith("__"):
                    continue

                if(first):
                    first = False
                else:
                    res += ", "

                res += attr + " = " + str( getattr(self, attr))

            res += ")"
            return res

    class Foo(stringMe):
        attribute_1 = None
        attribute_2 = None
        def __init__(self, value_1, value_2):
             self.attribute_1 = value_1
             self.attribute_2 = value_2


bar = Foo("baz", "ping")
print(str(bar)) # desired: Foo(attribute_1=baz, attribute_2=ping)