Trovo che molte classi che scrivo in Python contengano un piccolo insieme di variabili che in realtà mi piacerebbe vedere quando chiamo str()
e che riscrivere __str__(self)
per ciascuna è piuttosto ingombrante. Così, ho cucinato il seguente mixin,Python Mixin per __str__and Risoluzione dei metodi Ordine
class StrMixin(object):
'''
Automatically generate __str__ and __repr__
'''
def __str__(self):
import types
name = self.__class__.__name__ + ': '
attrs = [ '{}={}'.format(k,v) for (k,v) in self.__dict__.items() ]
return name + ', '.join(attrs)
def __repr__(self):
return str(self)
Tuttavia, se scrivo una classe,
class C(object, StrMixin):
pass
ottengo il seguente errore di un'istanza,
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution
order (MRO) for bases object, StrMixin
scontato, tra cui object
qui è ridondante, ma cosa sta succedendo davvero qui?
Se si desidera solo per ovviare a questo, considerare la possibilità di un decoratore, invece di un mixin. –