变量为空时给出的值

时间:2018-05-28 19:38:19

标签: python python-3.x

假设我有以下Player基类:

from abc import ABC, abstractmethod

class Player(ABC):

    def __init__(self, name, player_type):
        self.name = name
        self.player_type = player_type

Wizard

from Player import Player

class Wizard(Player):

    def __init__(self, name, player_type = "Wizard"):
        super().__init__(self,name)

Main

from Player import Player
from Wizard import Wizard


def main():

    gandalf = Wizard("Gandalf")
    print(gandalf.name)

    # Will print gandalf because the parameter assignment was shifted
    # because self was passed from the child to base class.
    print(gandalf.player_type)

if __name__ == "__main__":
    main()

我从this question知道,你不应该将self从子类传递给基类。话虽如此,假设您错误地这样做了,print(gandalf.name)行打印<Wizard.Wizard object at 0x049F20B0>,因为name从未被分配,但这个值究竟意味着什么?

1 个答案:

答案 0 :(得分:2)

super()不会返回课程;它返回一个代理对象,因此super().__init__(self, name)的行为与foo.__init__(self, name)非常相似,其中fooWizard的“真实”实例。在这种情况下,已经分配了对self的调用的第一个参数Player.__init__,因此您的显式 self已分配给下一个参数name和第二个参数name已分配给第三个参数player_type

换句话说,Player是MRO中的下一个班级,super().__init__(self, name)Player.__init__(self, self, name)相同。

换句话说,super().__init__是绑定方法,因此__init__函数的第一个参数self已经提供。