super()

Contents
Введение
Пример кода без super()
Пример применения super()
Похожие статьи

Введение

Пример создания похожих классов без super()

class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * self.length + 2 * self.width class Square: def __init__(self, length): self.length = length def area(self): return self.length * self.length def perimeter(self): return 4 * self.length square = Square(4) print(square.area()) rectangle = Rectangle(2,4) print(rectangle.area())

16 8

Пример применения super()

Гораздо короче можно инициализировать класс Square опираясь на уже существующий класс Rectangle

# Создадим класс Square который будет наследовать от класса Rectangle class Square(Rectangle): def __init__(self, length): super().__init__(length, length)

В этом примере super() использовался без явного указания аргументов. По умолчанию передаётся два аргумента - название класса и self.

class Rectangle: def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * self.length + 2 * self.width # Создадим класс Square который будет наследовать от класса Rectangle class Square(Rectangle): def __init__(self, length): super(Square, self).__init__(length, length) square = Square(4) print(square.area()) rectangle = Rectangle(2,4) print(rectangle.area())

Related Articles
OOP in Python
Classes
Methods
class variables
class methods
Static Methods
Inheritance
Special Methods
property decorator
Python
Functions
super()

Search on this site

Subscribe to @aofeed channel for updates

Visit Channel

@aofeed

Feedbak and Questions in Telegram

@aofeedchat