PYTHON CORE · LESSON 49

Name for each object

Method of __init__ · about 15 minutes

Learning with progressRead the summary for free. To save the work, log in to the account.
STEP 1

Different cats - different names

__init__ starts when an object is created. It receives name and stores it in self.name.

class Cat:
    def __init__(self, name):
        self.name = name

✦ self means this cat.

STEP 2

Pass on the name when you create it.

Now the name must be written in brackets Cat(). The object will remember its version.

pet = Cat("Мур")
print(pet.name)

✦ For the class, «Мур» will appear from the first step.

IN-CLASS PRACTICE

Type the code yourself

Dial class and object. Check the two indentation levels.

class Dog:
    def __init__(self, name):
        self.name = name
pet = Dog("Рекс")
print(pet.name)
Open the editor for class work
HOMEWORK

Solve it yourself

Create Cat with __init__(self, name), which saves name to self.name. Create a pet with the name «Мур» and output its name.

The answer is hidden. Use similar examples from the lesson notes.

Opening up your homework