2015-10-02 15 views
9

Zmęczony ręcznie wprowadzanie reprezentacji ciąg dla moich klas, zastanawiałem się, czy jest to pythonic sposób to zrobić automatycznie.Czy istnieje sposób automatycznego generowania implementacji __str __() w pythonie?

Chciałbym mieć wyjście, które obejmuje wszystkie atrybuty klasy i nazwy klasy. Oto przykład:

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 

Wynikające w:

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

To pytanie przyszło do głowy po użyciu projektu Lombok @ToString w niektórych projektach Java.

+0

Co Projekt Lombok dla Java? –

+0

Redukcja kodu kotła. Poszukaj funkcji: https://projectlombok.org/features/index.html –

+1

W rzeczywistości "redukcja kodu standardowego" nic nie znaczy. Lombok zajmuje się specyficznymi problemami Java. Szukanie "podobnego" narzędzia jest bezużyteczne, lepiej poprosić o coś bardziej konkretnego. –

Odpowiedz

16

Można iteracyjne instnace atrybuty używając 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

napisał natomiast falsetru answerred. Jej ten sam pomysł, kopalnia jest bardzo przyjazny początkujący jeśli chodzi o czytanie go, jego jest o wiele ładniejszy realizowane 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) 
Powiązane problemy