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 Method Arguments

Setting Attributes

What is the effect in where an attribute is set? Does it matter if the attribute is set right after defining the class versus after defining init()? If so, why?

This question came from a previous exercise on classes. What would be the difference between the following.

class RaceCar: laps = 0 # what is the difference between assigning laps here

def __init__(self, color, fuel_remaining, **kwargs):
    self.fuel_remaining = fuel_remaining
    self.color = color
    self.laps = 0                                                         # vs here
    for key, value in kwargs.items():
        setattr(self, key, value)

def run_lap(self, length):
    self.fuel_remaining = self.fuel_remaining - (length * .125)
    self.laps += 1

2 Answers

#An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks. Instance #variables are created when an object is instantiated, and are accessible to all the constructors, methods, or blocks in the #class. Access modifiers can be given to the instance variable.

class Student:
   name = None
   class = None
#class variables :is any variable declared on class level
# which a single copy exists, 
#regardless of how many instances of the class exist.

class Student:
    def __init__(self, name, class):
        self.name = name
        self.class= class

In the example you just gave, would self.name be considered a class variable?

Yes it is.

And about self.laps = 0

you just set the car laps to zero for every car you make from that class.