超级 parent class 并传递 class 变量的大多数 pythonic 方式

Most pythonic way to super parent class and pass class variables

我有一个 parent class 和一个 child class。 parent class 需要一些预定义的 class 变量到 运行 call()。 object 未在 child class 中定义。

问题:在调用super()而不改变parent[=32]时传递变量的最pythonic方式是什么=].

示例:

class Parent:
  def __init__(self):
    self.my_var = 0

  def call(self):
    return self.my_var + 1

class Child(Parent):
  def __init__(self):
    self.different_var = 1

  def call(self):
    my_var = 0
    super().__call__() # What is the most pythonic way of performing this line

我知道我可以在 child class 中制作 my_var 一个 class object 并且它会起作用,但必须有更好的.如果不是,那也是一个可以接受的答案。

你的版本只是一个mixin。你必须 __init__ super.

class Parent:
    def __init__(self):
        self.my_var = 0

    def call(self):
        return self.my_var + 1

class Child(Parent):
    def __init__(self):
        super().__init__()    #init super
        self.different_var = 1

    def call(self):
        self.my_var = 50
        return super().call() #return call() from super
        
c = Child()
print(c.call()) #51