super()

Содержание
Введение
Пример кода без 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

Banner image

Пример применения 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())

Article author: Andrei Olegovich

Похожие статьи
ООП в Python
Классы
Методы
class variables
class methods
Статические методы
Наследование
Специальные методы
dataclass
__slots__
Декоратор property
super()

Search this site

Subscribe to Telegram channel @aofeed to follow new articles and updates to old ones

Go to channel

@aofeed

Ask a question in the Telegram group

@aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: