0

For Code:

class Car(object):
   def __init__(self, make, model, year, color, engine_type):
     self.make = make
     self.model = model
     self.year = year
     self.color = color
     self.engine_type = engine_type

main():
  car1 = Car('Ford', 'Mustang', '2001', 'Red')
  print car1.make, car1.model, car1.year, car1.color

Is there a better/shorter way to print multiple variables (but not all of them such as using vars() or __dict__) from a class? Something like...

print car1.[make, model, year, color]

but that actually works?

2
  • You can do: print car1.make, car1.model, car1.year, car1.color Commented Aug 14, 2014 at 1:20
  • Consider pprint.pprint or getattr. Commented Aug 14, 2014 at 1:25

1 Answer 1

2

You could do something tricky like this:

attrs = ['make', 'model', 'year', 'color']
print " ".join(map(lambda attr: getattr(car1, attr), attrs))

I don't know if that's any better than what you have, though.

Sign up to request clarification or add additional context in comments.

1 Comment

Sounds like there's no shorthand for it, but the above code taught me lots thanks! Never have seen lambda or map before, I've only been coding for about 3 months

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.