PYTHON CORE · LESSON 50

Bottom line: cat says

My method in class. · about 18 minutes

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

The object can operate.

Method is a function within a class. His first argument is self: it is the object itself. Using self, the method can find out his name.

class Cat:
    def speak(self):
        return "Мяу!"

✦ Each Cat object will have a speak() action.

STEP 2

Call the method.

Create a class object from the first step and call its method through a point. In the task, combine this technique with a name from the previous lesson.

pet = Cat()
print(pet.speak())
How the object responds
ObjectpetMethodspeak()The resultМяу!

✦ For the class, «Мяу!» will appear from the first step. Think about adding a name instead.

IN-CLASS PRACTICE

Type the code yourself

Reprint the full class: name and action.

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

Solve it yourself

Create Cat: __init__ saves name to self.name, and speak returns «Мяу, » plus that name. Create pet with the name «Мур» and output the result pet.speak().

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

Opening up your homework