class: make a new type
Section 12: Classes and objects (class)Lesson 12.1 · ⏱ 12 min
Until now we made separate variables and functions. A class puts them together: the thing's data (its properties) and what it does (its functions). From one class we make many objects, just as we make many robots from one design.
__init__runs once when the object is made, and gives it its properties.selfmeans “this object itself”:self.batteryis this robot's battery.r1 = Robot("Robo", 50)makes a new object.r1.move(20)asks r1 to move, and r2 is not affected.
class Robot:
def __init__(self, name, battery):
self.name = name
self.battery = battery
def move(self, steps):
self.battery -= steps
print(self.name, "moved", steps, "steps. Battery:", self.battery)
def charge(self):
self.battery = 100
print(self.name, "is charged!")
r1 = Robot("Robo", 50)
r2 = Robot("Bibo", 80)
r1.move(20)
r2.move(5)
r1.charge()
print(r1.battery, r2.battery)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Robo moved 20 steps. Battery: 30 Bibo moved 5 steps. Battery: 75 Robo is charged! 100 75

📌 Another example: the circle class
class Circle keeps the radius, and works out the area.
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return round(3.14 * self.r * self.r, 2)
c = Circle(5)
print(c.area())
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗78.5
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
Test yourself
- Add a function
say(self, text)that prints the robot's name, then the text. - Make move print “Battery empty!” and not move if the battery is less than the steps.
🎯 Challenge yourself
Easy
A Dog class with a name, and a bark function that prints: Rex says woof.
👀 Show the solution🙈 Hide the solution
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name, "says woof")
Dog("Rex").bark()
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Rex says woof
Result: Rex says woof
Medium
A Rectangle class with area and perimeter.
👀 Show the solution🙈 Hide the solution
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
def area(self):
return self.w * self.h
def perimeter(self):
return 2 * (self.w + self.h)
r = Rectangle(4, 6)
print(r.area(), r.perimeter())
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗24 20
Result: 24 20
Hard
A BankAccount class: deposit and withdraw, and it doesn't withdraw more than it has.
👀 Show the solution🙈 Hide the solution
class BankAccount:
def __init__(self):
self.money = 0
def deposit(self, n):
self.money = self.money + n
def withdraw(self, n):
if n > self.money:
print("not enough money")
else:
self.money = self.money - n
a = BankAccount()
a.deposit(100)
a.withdraw(30)
a.withdraw(500)
print(a.money)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗not enough money 70
Result: not enough money, then 70

