Python reference
Classes and objects
Also called: class · object · __init__ · self · method · OOP
Definition
A class is a blueprint that bundles data (attributes) and behaviour (methods). Each object made from it has its own copy of the data; self refers to that object inside a method.
Picture it
Model each motor as a Motor object that remembers its own speed limit and current command, rather than juggling parallel lists. __init__ runs when an object is created and sets up its attributes.
Worked example
What does this print? class Motor: def __init__(self, max_rpm): self.max_rpm = max_rpm self.rpm = 0 def set_percent(self, p): self.rpm = self.max_rpm * p / 100 m = Motor(3000) m.set_percent(40) print(m.rpm)
- max_rpm = 3000
- rpm = 3000 × 40 / 100 = 1200.0
AnswerIt prints 1200.0.
✓ The number in this answer is recomputed from scratch by an automated test.
Common misconceptions
- Misconception: Forgetting self in a method's parameter list gives a confusing TypeError.
- Misconception: Attributes defined at class level are shared by every object; set per-object data in __init__.