A Class and Its Objects
In the lesson on dictionaries, you described a pet with a dictionary:
pet = {"name": "Rex", "species": "dog", "age": 3}One dictionary describes one pet. For every other pet, you write all the keys again, and nothing checks that each pet has the same ones: a typo such as "nmae" goes unnoticed. In this lesson, you'll write classes. A class says in one place what every pet has, and later also what every pet can do. From it, you then create as many pets as you like:
class Pet:
def __init__(self, name, species):
self.name = name
self.species = species
rex = Pet("Rex", "dog")
kiwi = Pet("Kiwi", "parrot")
print(rex.name)
print(kiwi.species)Rex
parrotLet's go through it:
class Pet:starts the class, and its body is indented below it. A class name is written in CapWords: each word starts with a capital letter, with no underscores (Pet,ShoppingCart). That's how you tell a class from a variable or a function.- In the body is a function with a special name,
__init__, with two underscores on each side. Python runs it by itself whenever a new pet is created, to set the pet up. - Its first parameter,
self, is the new pet itself.self.name = namestores the value of the parameternamein the pet. A value stored in an object like this is called an attribute. Pet("Rex", "dog")calls the class as if it were a function. Python creates a new object, runs__init__for it with the arguments and gives you the finished object, which you store in a variable.
You never pass self yourself: Python puts the new object there, and your arguments go into the other parameters, in order. You read an attribute with the object, a dot and the attribute's name: rex.name. Every object has its own attributes, so rex.name is "Rex" and kiwi.name is "Kiwi".
When an argument is missing, the program ends with an error, as it does with any function. Change the line that creates Rex to rex = Pet("Rex"), and you get:
Traceback (most recent call last):
File "<exec>", line 6, in <module>
TypeError: Pet.__init__() missing 1 required positional argument: 'species'Watch the underscores too. With only one on each side, _init_ is an ordinary function that Python doesn't run by itself, and Pet("Rex", "dog") ends with TypeError: Pet() takes no arguments.
Instructions
- 1
Below, print the sentence
Rex is a dog.Read the name and the species from the objectrex, for example in an f-string with{rex.name}. Keep the linerex = Pet("Rex", "dog")as it is. - 2
Create a second pet below it: Kiwi the parrot, in a variable
kiwi. Then print the same sentence for Kiwi:Kiwi is a parrot.