Lesson 1 · Unit 07
Classes
Make your own kind of value, with its own data and methods
What you practise
class,__init__,self, attributes and methods, many instances of one class,__repr__and__eq__
Try a question from this lesson
Pick one
A class is a pattern for making values of your own kind. Dog("Rex") makes one dog and hands "Rex" to __init__. What does this program show?
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof"
rex = Dog("Rex")
print(rex.speak())Hint
Line 3 stores the name on the new dog. Line 6 reads it back.
Correct answer
Rex says woof
Why
Making the dog runs __init__, which stores "Rex" on the new dog as self.name. Later, rex.speak() reads that stored name. self is the dog the method is working on: here, the one called rex.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Classes and objects
A class is the pattern. A value made from it is an object.
__init__ runs once for each new object, to set it up. self is that object. self.name = name stores a value on it: an attribute.
A function inside a class is a method. You call it on an object, with a dot.
class Dog:
def __init__(self, name):
self.name = name # attribute
def speak(self): # method
return f"{self.name} says woof"
rex = Dog("Rex") # an object
print(rex.name) # RexConcept
What self is
When you call a method on an object, Python passes that object in as the first argument.
So rex.speak() is a short way of writing Dog.speak(rex). Inside the method, self is rex.
That is why every method lists self first, and why you never pass it yourself.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return self.name + " says woof"
rex = Dog("Rex")
print(rex.speak()) # Rex says woof
print(Dog.speak(rex)) # the same callConcept
Saying what equal means
== on two objects calls the method __eq__. The object on the left is self, the one on the right is other.
Return True when the parts that matter are equal. Now two points with the same numbers are equal.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return (self.x == other.x
and self.y == other.y)
print(Point(1, 2) == Point(1, 2)) # True9 more exercises in the app
- 3× type the answer
- 2× fill the blanks
- 2× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.