简体   繁体   中英

Most pythonic way to super parent class and pass class variables

I have a parent class and a child class. The parent class needs some predefined class variables to run call() . The objects are not defined in the child class.

Question: What is the most pythonic way to pass the variables when calling super() without changing the parent class .

Example:

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

I know I could just make my_var in the child class a class object and it would work, but there must be a better. If not that would be an acceptable answer as well.

Your version is just a mixin. You have to __init__ the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM