Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Superclass | Inheritance
In-Depth Python OOP
course content

Зміст курсу

In-Depth Python OOP

Superclass

In Python, a superclass is a class that is inherited from by other classes. It serves as the parent class or base class, providing attributes and methods that can be inherited and utilized by its subclasses. They provide a way to define common functionality and characteristics that can be shared among multiple related classes.

The super() function in Python is used to access and invoke methods or attributes from a superclass within a subclass. It provides a convenient way to delegate or call the superclass's implementation of a method. By using super(), you can call a method defined in the parent class, even if the method has been overridden in the child class. This allows for code reuse and facilitates the extension or customization of the parent class's behavior.

The super() function is typically used inside a subclass to call the parent class's methods. It takes two arguments: the subclass itself (usually self) and the subclass instance (optional). When called without any arguments, super() returns a temporary object of the superclass. You can then call methods or access attributes on this object using dot (.). This provides a way to selectively override or extend the behavior of the parent class while still benefiting from its existing functionality.

The provided code defines two classes: User and NewUser.

The User class has a constructor method __init__() that takes two parameters, username and password. The NewUser class is a subclass of User and extends it by adding additional attributes: name, surname, and age.

The __init__() method in the NewUser class takes five parameters: username, password, name, surname, and age. It calls the __init__() method of the parent class (User) using super().__init__(username, password) to initialize the username and password attributes inherited from the User class. It then sets the name, surname, and age attributes using the provided values.

Note

You can use the super() function for other methods and attributes. The super() call methods from the Parent class and use Parent attributes. This allows us to extend parent methods.

One more example:

Note

The super() function is used by popular frameworks like Django.

Все було зрозуміло?

Секція 2. Розділ 5
We're sorry to hear that something went wrong. What happened?
some-alt