Python中的默认方法实现(__str__, __eq__, __repr__, 等)

6 投票
1 回答
2144 浏览
提问于 2025-04-17 05:14

有没有简单的方法可以为一个类添加__str____eq____repr__的实现呢?

基本上,我想让__eq__的功能就是判断所有没有前缀的实例变量是否相等。
__str____repr__的功能就是列出每个变量的名字,并对每个变量调用str/repr。
在标准库中有没有这样的机制呢?

1 个回答

12

你可以定义一个叫做 Default 的混合器:

class Default(object):
    def __repr__(self):
        return '-'.join(
            str(getattr(self,key)) for key in self.__dict__ if not key.startswith('_'))
    def __eq__(self,other):
        try:
            return all(getattr(self,key)==getattr(other,key)
                       for key in self.__dict__ if not key.startswith('_'))
        except AttributeError:
            return False


class Foo(Default):
    def __init__(self):
        self.bar=1
        self.baz='hi'

foo=Foo()
print(foo)
# hi-1

foo2=Foo()
print(foo==foo2)
# True

foo2.bar=100
print(foo==foo2)
# False

撰写回答