Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Instant Objects Master Class

Sahil Kapoor
Sahil Kapoor
8,932 Points

What does the question says to do with setattr?

Didn't understand what is the question saying to do with setattr The question is ... OK, let's combine everything we've done so far into one challenge! First, create a class named RaceCar. In the init for the class, take arguments for color and fuel_remaining. Be sure to set these as attributes on the instance. Also, use setattr to take any other keyword arguments that come in.

racecar.py
class RaceCar:
    def __init__(self, color, fuel_remaining):
        self.color = color
        self.fuel_remaining = fuel_remaining

3 Answers

Omar Farag
Omar Farag
4,573 Points

setattr() takes 3 arguments. The instance to use it on (self), and then takes a dictionary and uses the key as the attribute name and the value as an attribute value.

class RaceCar:
    def __init__(self, color, fuel_remaining, **kwargs):
        self.color = color
        self.fuel_remaining = fuel_remaining
        for key, value in kwargs.items():
              setattr(self, key, value)
Omar Farag
Omar Farag
4,573 Points

Let's say i gave in {name: "Omar", question: 'answered'}. It would set two new attributes to self, those being: self.name = 'Omar' self.question = 'answered'

What this does?

self.color = color

class RaceCar:

def __init__(self, color, fuel_remaining, **kwargs):
    self.color = color
    self.fuel_remaining = fuel_remaining
    for key, value in kwargs.items():
        setattr (self, key, value)