Перевод параграфа 6.4 Inheritance из книги Intermediate Python.
Наследование — это механизм создания новых классов. Наследники специализируют или изменяют базовые классы добавляя в них новую функциональность. Python поддерживает множественное наследование как C++. Пример одиночного наследования в Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class Account: """base class for representing user accounts""" num_accounts = 0 def __init__(self, name, balance): self.name = name self.balance = balance Account.num_accounts += 1 def del_account(self): Account.num_accounts -= 1 def __getattr__(self, name): """handle attribute reference for non-existent attribute""" return "Hey I dont see any attribute called {}".format(name) def deposit(self, amt): self.balance = self.balance + amt def withdraw(self, amt): self.balance = self.balance - amt def inquiry(self): return "Name={}, balance={}".format(self.name, self.balance) class SavingsAccount(Account): def __init__(self, name, balance, rate): super().__init__(name, balance) self.rate = rate def __repr__(self): return "SavingsAccount({}, {}, {})".format(self.name, self.balance, self.rate) |
1 2 3 |
>>>acct = SavingsAccount("Obi", 10, 1) >>>repr(acct) SavingsAccount(Obi, 10, 1) |