Python default method implementations (__ str __, __ eq __, __ repr __, ect.)

Is there a way to add a simple implementation for __str__, __eq__, __repr__in the class?

Basically, I want it to __eq__consist only in whether all instance variables are equal without a prefix.
And __str__/ __repr__, which simply names each variable and calls str / repr for each variable.
Is there a mechanism for this in the standard library?

+5
source share
1 answer

You can define Defaultmixin:

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
+10
source

All Articles