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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With