Pythonでは、スーパークラスからサブクラスをどのように作成しますか?
Pythonでは、スーパークラスからサブクラスをどのように作成しますか?
回答:
# Initialize using Parent
#
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
または、さらに良いことに、Pythonの組み込み関数の使用super()
(Python 2 / Python 3のドキュメントを参照)は、初期化のために親を呼び出すための少し良い方法かもしれません。
# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
または、super()
クラス定義内でのみ機能する、のゼロ引数形式を使用することを除いて、上記とまったく同じです。
class MySubClassBetter(MySuperClass):
def __init__(self):
super().__init__()
super
特に新しいPythonプログラマー(Lutzなど)に対して警告する人もいます。私はそれを避けます。
super
はsuper
、Pythonでの動作と、他の言語でのsuper
/のparent
動作の違いを理解していない場合です。確かに、これは他の言語から来た人々には明らかではありませんが、それが「注意」の対象となるとは結論付けません。それは機能します。動作が異なります。予期しない結果が得られることについて文句を言う前に、Pythonで実際に何が行われるかを読んでください。
英雄的な小さな例:
class SuperHero(object): #superclass, inherits from default object
def getName(self):
raise NotImplementedError #you want to override this on the child classes
class SuperMan(SuperHero): #subclass, inherits from SuperHero
def getName(self):
return "Clark Kent"
class SuperManII(SuperHero): #another subclass
def getName(self):
return "Clark Kent, Jr."
if __name__ == "__main__":
sm = SuperMan()
print sm.getName()
sm2 = SuperManII()
print sm2.getName()
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
# <the rest of your custom initialization code goes here>
継承のセクションPythonドキュメントでは、より詳細にそれを説明します
__init__
さらにコードを追加する場合にのみ、そのメソッドを定義する必要があります。それ以外の場合は、元のinitメソッドが使用されます(ただし、言及する価値があり、完全に有効なコードです)
上記の回答では、super
は(キーワード)引数なしで初期化されます。ただし、多くの場合、それを実行したり、独自の「カスタム」引数を渡したりする必要があります。このユースケースを説明する例を次に示します。
class SortedList(list):
def __init__(self, *args, reverse=False, **kwargs):
super().__init__(*args, **kwargs) # Initialize the super class
self.reverse = reverse
self.sort(reverse=self.reverse) # Do additional things with the custom keyword arguments
これはサブクラスでlist
あり、初期化されるreverse
と、次のテストが示すように、キーワード引数で指定された方向にすぐにソートされます。
import pytest
def test_1():
assert SortedList([5, 2, 3]) == [2, 3, 5]
def test_2():
SortedList([5, 2, 3], reverse=True) == [5, 3, 2]
def test_3():
with pytest.raises(TypeError):
sorted_list = SortedList([5, 2, 3], True) # This doesn't work because 'reverse' must be passed as a keyword argument
if __name__ == "__main__":
pytest.main([__file__])
上の通過のおかげ*args
にはsuper
、リストが初期化され、代わりにのみ、空であることの項目を移入することができます。(これreverse
は、PEP 3102に準拠したキーワードのみの引数であることに注意してください)。
class BankAccount:
def __init__(self, balance=0):
self.balance = int(balance)
def checkBalance(self): ## Checking opening balance....
return self.balance
def deposit(self, deposit_amount=1000): ## takes in cash deposit amount and updates the balance accordingly.
self.deposit_amount = deposit_amount
self.balance += deposit_amount
return self.balance
def withdraw(self, withdraw_amount=500): ## takes in cash withdrawal amount and updates the balance accordingly
if self.balance < withdraw_amount: ## if amount is greater than balance return `"invalid transaction"`
return 'invalid transaction'
else:
self.balance -= withdraw_amount
return self.balance
class MinimumBalanceAccount(BankAccount): #subclass MinimumBalanceAccount of the BankAccount class
def __init__(self,balance=0, minimum_balance=500):
BankAccount.__init__(self, balance=0)
self.minimum_balance = minimum_balance
self.balance = balance - minimum_balance
#print "Subclass MinimumBalanceAccount of the BankAccount class created!"
def MinimumBalance(self):
return self.minimum_balance
c = BankAccount()
print(c.deposit(50))
print(c.withdraw(10))
b = MinimumBalanceAccount(100, 50)
print(b.deposit(50))
print(b.withdraw(10))
print(b.MinimumBalance())