当类没有指定超类时,为什么要使用super()?

2024-05-18 11:16:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我理解当类是超类的子类时为什么要使用super(),但是在子类参数中没有指定超类的类的超类是什么?我的代码是:

import random


class Sneaky:
    sneaky = True

    def __init__(self, sneaky=True, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.sneaky = sneaky

    def hide(self, light_level):
        return self.sneaky and light_level < 10


class Agile:
    agile = True

    def __init__(self, agile=True, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.agile = agile

    def evade(self):
        return self.agile and random.randint(0, 1)

Tags: selftruereturninitdefargsrandom子类
1条回答
网友
1楼 · 发布于 2024-05-18 11:16:04

假设Sneaky用作多重继承类结构的一部分,例如:

class Sneaky:
    sneaky = True

    def __init__(self, sneaky=True, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.sneaky = sneaky

    def hide(self, light_level):
        return self.sneaky and light_level < 10

class Person:
    def __init__(self, human=True, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.human = human

class Thief(Sneaky, Person): 
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


t = Thief()
print(t.human)
# True

因为

^{pr2}$
  • Thief.__init__super().__init__(*args, **kwargs)调用Sneaky.__init__。在
  • Sneaky.__init__super().__init__(*args, **kwargs)调用Person.__init__。在

如果super().__init__调用从Sneaky.__init__中删除,那么{}将引发

AttributeError: 'Thief' object has no attribute 'human'

因为Person.__init__不会被调用。在

相关问题 更多 >