2015-10-02 11 views
9

Essendo stanco di implementare manualmente una rappresentazione di stringhe per le mie classi, mi chiedevo se esiste un modo pititico per farlo automaticamente.C'è un modo per generare automaticamente un'implementazione __str __() in python?

Mi piacerebbe avere un output che copra tutti gli attributi della classe e il nome della classe. Ecco un esempio:

class Foo(object): 
    attribute_1 = None 
    attribute_2 = None 
    def __init__(self, value_1, value_2): 
     self.attribute_1 = value_1 
     self.attribute_2 = value_2 

Con conseguente:

bar = Foo("baz", "ping") 
print(str(bar)) # desired: Foo(attribute_1=baz, attribute_2=ping) 

Questa domanda è venuto in mente dopo l'utilizzo di Project Lombok @ToString in alcuni progetti Java.

+0

Quale progetto Lombok fa per Java? –

+0

Riduzione del codice della piastra di riscaldamento. Guardate qui per le caratteristiche: https://projectlombok.org/features/index.html –

+1

In realtà, "la riduzione del codice boilerplate" significa nulla. Lombok si occupa di problemi specifici di Java. È inutile cercare uno strumento "simile", è meglio chiedere qualcosa di più concreto. –

risposta

16

È possibile scorrere instnace attributi utilizzando vars, dir, ...:

>>> def auto_str(cls): 
...  def __str__(self): 
...   return '%s(%s)' % (
...    type(self).__name__, 
...    ', '.join('%s=%s' % item for item in vars(self).items()) 
...  ) 
...  cls.__str__ = __str__ 
...  return cls 
... 
>>> @auto_str 
... class Foo(object): 
...  def __init__(self, value_1, value_2): 
...   self.attribute_1 = value_1 
...   self.attribute_2 = value_2 
... 
>>> str(Foo('bar', 'ping')) 
'Foo(attribute_2=ping, attribute_1=bar)' 
1

ha scritto questo mentre falsetru answerred. sua stessa idea, la mia è molto principiante amichevole in termini di lettura, il suo è molto più bello implementato imho

class stringMe(object): 
     def __str__(self): 
      attributes = dir(self) 
      res = self.__class__.__name__ + "(" 
      first = True 
      for attr in attributes: 
       if attr.startswith("__") and attr.endswith("__"): 
        continue 

       if(first): 
        first = False 
       else: 
        res += ", " 

       res += attr + " = " + str(getattr(self, attr)) 

      res += ")" 
      return res 

    class Foo(stringMe): 
     attribute_1 = None 
     attribute_2 = None 
     def __init__(self, value_1, value_2): 
      self.attribute_1 = value_1 
      self.attribute_2 = value_2 


bar = Foo("baz", "ping") 
print(str(bar)) # desired: Foo(attribute_1=baz, attribute_2=ping) 
Problemi correlati