Classes
Programming Languages · Python Functions & Data · 14 min
Make your own types of objects that bundle data and actions together.
A class is a blueprint
A class is a blueprint. An object is one thing built from it. Make an object by calling the class like a function:
class Robot:
color = "silver"
bot = Robot()
print(bot.color) # silver
The dot means "look inside": bot.color is the color that belongs to bot.
Define a class
Dogwithsound = "Woof"inside it.Create a
Dogobject calledrexand printrex.sound.
__init__ and attributes
__init__ is a special function that runs when an object is made. Use it to give each object its own data, called attributes. self means "this object".
class Robot:
def __init__(self, name):
self.name = name
bot = Robot("Beep")
print(bot.name) # Beep
Replace
passwith an__init__(self, name)that storesnameinself.name.Create
rex = Dog("Rex")and printrex.name.
Methods
A method is a function that lives inside a class. Its first parameter is always self, so it can use the object's attributes. Call it with a dot:
class Robot:
def __init__(self, name):
self.name = name
def beep(self):
print(f"{self.name}: beep!")
Robot("Bo").beep() # Bo: beep!
Add a method
bark(self)that prints the dog's name followed bysays Woof!.Create
rex = Dog("Rex")and callrex.bark().
Many objects, one class
The real power of a class: build as many objects as you like from it. Each one keeps its own attributes.
a = Robot("Beep")
b = Robot("Boop")
a.beep() # Beep: beep!
b.beep() # Boop: beep!
Create
tom = Cat("Tom", 3)andkit = Cat("Kit", 1).Call
describe()on both cats.
Put it together: bank accounts
Build a tiny bank. Each Account has an owner and a balance that starts at 0. A deposit method adds money. Then open two accounts and put some money in.
Write
class Accountwith__init__(self, owner)that storesself.ownerand setsself.balanceto 0.Add a method
deposit(self, amount)that addsamounttoself.balance.Make accounts for
"Ada"and"Bo". Ada deposits 50 and then 25, Bo deposits 10. Print each asAda: 75.
More in Python Functions & Data
Previous: Dictionaries · Next: Advanced OOP