• 12 heures
  • Facile

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 18/04/2024

Write a Subclass in Python

Define the Subclassing Syntax

The main piece of syntax used for defining subclasses is in the class definition itself:  class Employee(Person) . The class’s parent is bracketed after the class’s name in the first line of the class. 

class TextContactSystem(ContactSystem):
    def __init__(self, phone_number):
        self.phone_number = phone_number
 
    def send(self, message):
        send_text_message(self.phone_number,message)

In the case of multiple inheritances - which we’ll briefly touch on later in Chapter 4 - the parent classes are separated by brackets, similar to the way parameters to functions work, like this:  class Subclass(ParentOne,ParentTwo)...

Your Turn: Write Code Using Inheritance

Context: 

In this exercise, you'll be building a basic structure for an online web forum, the classes you defined in the last chapter. Your task is to define several classes to represent different entities within the forum system and implement their behaviors. This exercise will help you practice inheritance and class design in Python.

Instructions: 

In your development environment, write a class definition for each of those classes (using subclasses where relevant).

Assume that, for now, you’re just printing a post’s content to the terminal. We’ll deal with displaying threads later, so just use pass for that method for now.

When you don’t know how to implement a method, you can use  pass as that method’s body. Use your judgment when implementing these methods. Remember to include constructors for each class!

Let’s Recap!

  • Define a child class using  class Child(Parent).

  • By default, all classes inherit from an object - a Python object that provides basic functionality.

  • It’s possible for classes to inherit from multiple parent classes at once - in multiple inheritance.

Now that you have your subclasses, join us in the next chapter, where we use overriding to allow subclasses to have different behavior than their parents.

Exemple de certificat de réussite
Exemple de certificat de réussite