Python中的默认方法实现(__str__, __eq__, __repr__, 等)
有没有简单的方法可以为一个类添加__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