【问题标题】:Redefine __str__ method in the same way for multiple classes in Python以相同的方式为 Python 中的多个类重新定义 __str__ 方法
【发布时间】:2020-12-15 02:03:31
【问题描述】:

我有多个类,如果我实例化其中的任何一个,我希望能够通过为这些类重新定义 str 方法来“打印”实例化的对象。 str 方法对于所有类都是完全相同的,我不想在每个类下都重复这个方法。如何为所有类执行此操作,而不必在每个类下定义 str?类装饰器会在这里提供帮助吗?

class testClass1:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return(self.value + 5)

class testClass2:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return(self.value + 5)

test1 = testClass1(2)
print(test1)

【问题讨论】:

  • 你可以创建一个类装饰器,或者你使用继承。

标签: python class object methods printing


【解决方案1】:

您可以定义一个具有您想要的功能的父类并在每个子类中继承它:

class Stringer:
    def __str__(self):
        return(str(self.value + 5))
    
class testClass1(Stringer):
    def __init__(self, value):
        self.value = value

class testClass2(Stringer):
    def __init__(self, value):
        self.value = value

test1 = testClass1(2)
print(test1)
#7 

test2 = testClass2(5)
print(test2)
#10 

【讨论】:

  • 是的,这行得通。我想知道是否有办法在没有继承的情况下做到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-27
  • 2013-12-13
  • 2012-04-07
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 2020-09-23
相关资源
最近更新 更多