关于类:Python:如何从超类创建子类?

Python: How do I make a subclass from a superclass?

在Python中,如何从超类创建子类?


1
2
3
4
5
# Initialize using Parent
#
class MySubClass(MySuperClass):
    def __init__(self):
        MySuperClass.__init__(self)

或者,更好的是,使用python的内置函数super()(请参阅python 2/python 3文档)可能是一种更好的方法,可以调用父级进行初始化:

1
2
3
4
5
# Better initialize using Parent (less redundant).
#
class MySubClassBetter(MySuperClass):
    def __init__(self):
        super(MySubClassBetter, self).__init__()

或者,与上面一样,只是使用了super()的零参数形式,它只在类定义中工作:

1
2
3
class MySubClassBetter(MySuperClass):
    def __init__(self):
        super().__init__()


一个英雄的小例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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()


1
2
3
4
5
class MySubClass(MySuperClass):
    def __init__(self):
        MySuperClass.__init__(self)

        # <the rest of your custom initialization code goes here>

python文档中关于继承的部分更详细地解释了它。


1
2
3
4
5
class Class1(object):
    pass

class Class2(Class1):
    pass

第2类是第1类的一个子类


在上面的答案中,super是在没有任何(关键字)参数的情况下初始化的。然而,通常情况下,您希望这样做,同时传递一些您自己的"自定义"参数。下面是一个示例,说明了这个用例:

1
2
3
4
5
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关键字参数指定的方向对自己排序,如下测试所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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,列表可以初始化和填充项目,而不只是空的。(注意,根据PEP 3102,reverse是一个只包含关键字的参数)。


还有另一种方法可以使用函数type()在python中动态生成子类:

1
SubClass = type('SubClass', (BaseClass,), {'set_x': set_x})  # Methods can be set, including __init__()

在处理元类时,通常要使用此方法。当您想要执行一些较低级别的自动化时,这会改变Python创建类的方式。很可能你不需要这样做,但是当你这样做的时候,你已经知道你在做什么了。


您使用:

1
class DerivedClassName(BaseClassName):

有关详细信息,请参见第9.5节的python文档。


1
2
class Subclass (SuperClass):
      # Subclass stuff here

1
2
3
4
5
class Mammal(object):
#mammal stuff

class Dog(Mammal):
#doggie stuff

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
34
35
36
37
38
39
40
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())


python中的子类化操作如下:

1
2
3
4
5
6
7
class WindowElement:
    def print(self):
        pass

class Button(WindowElement):
    def print(self):
        pass

下面是一个关于Python的教程,其中也包含类和子类。