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 trialNicholas Abate
1,643 PointsSetting 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?
2 Answers
Mohammad Azawi
Courses Plus Student 5,631 Points#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
Nicholas Abate
1,643 PointsIn the example you just gave, would self.name be considered a class variable?
Mohammad Azawi
Courses Plus Student 5,631 PointsYes it is.
And about self.laps = 0
you just set the car laps to zero for every car you make from that class.
Nicholas Abate
1,643 PointsNicholas Abate
1,643 PointsThis 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