在Python中,如何从超类中创建子类?
答案 0 :(得分:79)
# 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__()
答案 1 :(得分:61)
一个英雄的小例子:
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()
答案 2 :(得分:36)
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
# <the rest of your custom initialization code goes here>
python文档中的section on inheritance更详细地解释了它
答案 3 :(得分:14)
class Class1(object):
pass
class Class2(Class1):
pass
第2类是第1类的子类
答案 4 :(得分:6)
在上面的答案中,super
初始化时没有任何(关键字)参数。但是,通常情况下,您希望这样做,并传递一些&#39; custom&#39;你自己的论点。下面是一个说明此用例的示例:
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)。
答案 5 :(得分:4)
还有另一种方法可以使用函数type()
动态地在python中创建子类:
SubClass = type('SubClass', (BaseClass,), {'set_x': set_x}) # Methods can be set, including __init__()
使用元类时,通常需要使用此方法。当你想做一些较低级别的自动化时,这会改变python创建类的方式。很可能你不需要这样做,但是当你这样做时,你已经知道你在做什么了。
答案 6 :(得分:3)
class Subclass (SuperClass):
# Subclass stuff here
答案 7 :(得分:3)
答案 8 :(得分:2)
class Mammal(object):
#mammal stuff
class Dog(Mammal):
#doggie stuff
答案 9 :(得分:1)
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())
答案 10 :(得分:0)
Python中的子类化完成如下:
class WindowElement:
def print(self):
pass
class Button(WindowElement):
def print(self):
pass
这是关于Python的tutorial,它还包含类和子类。