Lesson 2 of 15 · Classes and Objects
Defining a Class
Write your first Python class step by step: the class keyword, creating objects, giving them attributes, adding methods and understanding self.
- 9 min read
- Intermediate
- Reviewed
- How to write a class with the class keyword
- How to create objects from a class
- How to store data on an object
- How to add a method and what self means
The smallest possible class
A class starts with the keyword class, then a name, then a colon. Everything that belongs to the class is indented underneath, just like the body of a function or a loop.
class Dog:
pass
rex = Dog()
bella = Dog()
print(rex)
print(type(rex))pass is a keyword that means "do nothing". Python needs at least one line inside a class, and pass is a placeholder.
Two important things happened:
class Dog:created the blueprint. On its own, it does nothing.Dog()creates an object from the blueprint.
The first print shows something like <__main__.Dog object at 0x7f...>. That is Python's default way of describing an object: its class and its address in the computer's memory. You will learn to replace it with something friendlier later in the course.
Naming classes
Examples: Dog, BankAccount, ChatMessage. This makes classes easy to tell apart from variables and functions, which use snake_case.
Every object is separate
rex and bella were made from the same class, but they are two different objects.
class Dog:
pass
rex = Dog()
bella = Dog()
print(rex is bella)
print(rex is rex)is checks whether two names point to the same object. They do not: each call to Dog() builds a brand-new one, just as each press of a cookie cutter makes a new cookie.
Giving objects data
You can attach data to an object with a dot, like sticking a label on it: object.name = value. Remember, a piece of data stored on an object is called an attribute.
class Dog:
pass
rex = Dog()
rex.name = "Rex"
rex.age = 3
bella = Dog()
bella.name = "Bella"
bella.age = 5
print(rex.name, rex.age)
print(bella.name, bella.age)Each dog keeps its own attributes. Changing rex.age has no effect on bella.
Setting attributes from outside like this is fine for learning, but it is error-prone: nothing guarantees every dog gets a name. In the next lesson you will learn the proper way, where the class itself sets up every new object.
Adding a method
A method is a function written inside a class. It is an action the class's objects can perform.
class Dog:
def bark(self):
print("Woof!")
rex = Dog()
rex.bark()You call a method with a dot, on an object: rex.bark().
What is self?
Look at the method again: def bark(self):. When you call rex.bark(), Python automatically passes rex in as self. You never pass it yourself.
That is how a method can use the object's own data:
class Dog:
def bark(self):
print(f"{self.name} says Woof!")
rex = Dog()
rex.name = "Rex"
bella = Dog()
bella.name = "Bella"
rex.bark()
bella.bark()When rex.bark() runs, self is rex, so self.name is "Rex". When bella.bark() runs, self is bella. One method, written once, works for every dog.
A helpful way to picture it: rex.bark() is a shortcut for Dog.bark(rex). Both lines do exactly the same thing.
class Dog:
def bark(self):
print(f"{self.name} says Woof!")
rex = Dog()
rex.name = "Rex"
rex.bark()
Dog.bark(rex)You will always write the short form, but knowing the long form explains where self comes from.
A method with extra parameters
Methods can take more parameters after self. You pass only those when you call the method. Python fills in self for you.
class Dog:
def describe(self):
return f"{self.name} is {self.age} years old"
def birthday(self):
self.age = self.age + 1
def fetch(self, item, times):
for _ in range(times):
print(f"{self.name} brings back the {item}")
rex = Dog()
rex.name = "Rex"
rex.age = 3
rex.fetch("ball", 2)
rex.birthday()
print(rex.describe())Notice three different kinds of method:
describe()returns information about the object.birthday()changes the object's data.fetch()takes extra arguments:rex.fetch("ball", 2)passes"ball"asitemand2astimes.
Common mistakes
Write your first class, with one method that changes the object and one that reports on it.
# 1. Write a class called Lamp with two methods: # switch_on(self) sets self.is_on to True # status(self) returns "on" or "off" depending on self.is_on # 2. The code below must then print exactly: # Desk lamp is off # Desk lamp is on lamp = Lamp() lamp.name = "Desk lamp" lamp.is_on = False print(lamp.name, "is", lamp.status()) lamp.switch_on() print(lamp.name, "is", lamp.status())
When you call rex.bark(), what is self inside the bark method?
Summary
class Name:defines a class. Class names use PascalCase.Name()creates a new, separate object from the class.object.attribute = valuestores data on an object.- A method is a function inside a class. Its first parameter is always
self. selfis the object the method was called on, soself.namereads that object's data.
Next: the special method that sets up every new object automatically.
Finished reading? Tick it off to track your progress.