- Removing Need For Repeated Definition of __str__

Dylan Moreland dylan.moreland at gmail.com
Mon Apr 3 09:21:34 EDT 2006


Ilias Lazaridis wrote:
> I have some python code which looks similar to this:
>
> class Car(BaseClass) :
>        manufacturer = factory.string()
>        model = factory.string()
>        modelYear = factory.integer()
>
>        def __str__(self):
>            return '%s %s %s' % (self.modelYear, self.manufacturer,
> self.model)
>
> def factory.string(self)
>       s = String()     # creates a string object
>       #...             # does several things
>       return s         # returns the string object
>
> -
>
> I would like to simplify it in this way:
>
> class Car(BaseClass):
>        manufacturer = factory.string(2)  # 2 = position number...
>        model = factory.string(3)         # ...withinn __str__
>        modelYear = factory.integer(1)
>
> def factory.string(self, position)
>       s = String()     # creates a string object
>       ...              # does several things
>
       # creates somehow the __str__ functionality...
>
>       return s         # returns the string object
>
> -
>
> How could I achieve this?
>
> .
>

I'm slightly confused about your use of factory functions for making
instance variables (perhaps you could explain that?). Without knowing
more about that, here's a mixin solution I've used in the past (note
that __strdef__ is something I just made up):

class SmartStr(object):

    def __str__(self):
        return "<%s %s>" % (self.__class__.__name__,
            ", ".join(attrname + "=" + str(getattr(self, attrname))
                      for attrname in self.__strdef__))

class Car(SmartStr):

    __strdef__ = ["model_year", "manufacturer", "model"]

    def __init__(self, manufacturer, model, model_year):
        self.manufacturer = manufacturer
        self.model = model
        self.model_year = model_year

c = Car("Toyota", "Camry", 1990)
print c # => <Car model_year=1990, manufacturer=Toyota, model=Camry>




More information about the Python-list mailing list