Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default method implementations in python(__str__,__eq__,__repr__,ect.)

Are there any ways to add a simple implementations for __str__,__eq__,__repr__ to a class?

Basically I want an __eq__ to be just be whether all non prefixed instance variables are equal.
And a __str__/__repr__ that just names each variable and calls str/repr on each variable.
Is there a mechanism for this in the standard library?

like image 276
Roman A. Taycher Avatar asked Oct 29 '11 09:10

Roman A. Taycher


1 Answers

You could define a Default mixin:

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
like image 152
unutbu Avatar answered Sep 23 '22 22:09

unutbu