[CONSTRUCT] - Removing Need For Repeated Definition of __str__

  • Thread starter Ilias Lazaridis
  • Start date
I

Ilias Lazaridis

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?

..
 
D

Dylan Moreland

Ilias said:
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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top