Da Ihre __str__
und __repr__
dem gleichen Muster folgen, könnten Sie Schreiben Sie eine Funktion, um die String-Repräsentation für Sie zu erstellen. Es wäre ein Objekt, eine Liste der Attribute nehmen und str
oder repr
als Argument:
def stringify(obj, attrs, strfunc):
values = []
# get each attribute's value and convert it to a string
for attr in attrs:
value = getattr(obj, attr)
values.append(strfunc(value))
# get the class name
clsname = type(obj).__name__
# put everything together
args = ', '.join(values)
return '{}({})'.format(clsname, args)
print(stringify(MyClass('foo'), ['a'], repr))
# output: MyClass('foo')
Ich würde empfehlen, diese Funktion in einer Klasse setzen, die Sie dann erben von:
class Printable:
def __str__(self):
return self.__stringify(str)
def __repr__(self):
return self.__stringify(repr)
def __stringify(self, strfunc):
values = []
for attr in self._attributes:
value = getattr(self, attr)
values.append(strfunc(value))
clsname = type(self).__name__
args = ', '.join(values)
return '{}({})'.format(clsname, args)
class MyClass(Printable):
_attributes = ['a']
def __init__(self, a):
self.a = a
Und Sie können es sogar vollautomatisch erledigen, indem Sie die Attribute direkt aus der Signatur der __init__
Funktion übernehmen:
import inspect
class AutoPrintable:
def __str__(self):
return self.__stringify(str)
def __repr__(self):
return self.__stringify(repr)
def __stringify(self, strfunc):
sig= inspect.signature(self.__init__)
values= []
for attr in sig.parameters:
value= getattr(self, attr)
values.append(strfunc(value))
clsname= type(self).__name__
args= ', '.join(values)
return '{}({})'.format(clsname, args)
class MyClass(AutoPrintable):
def __init__(self, a, b):
self.a = a
self.b = b
print(str(MyClass('foo', 'bar'))) # output: MyClass(foo, bar)
print(repr(MyClass('foo', 'bar'))) # output: MyClass('foo', 'bar')
Ist es wirklich notwendig, dass 'str' und' repr' zwei verschiedene Strings zurückgeben? –
Sie könnten einfach "__str__ = __repr__" (oder umgekehrt) sagen, um die Implementierung zu kopieren. – jasonharper
Es ist nicht notwendig, dass sie unterschiedliche Zeichenfolge zurückgeben, aber oft vorzuziehen. Vielleicht ist dieses Beispiel einfach zu vermitteln. –