简体   繁体   English

在Python中覆盖从父类继承的多个属性

[英]override multiple attributes inherited from parent class in Python

I'd like to assign different values to inherited attributes in the instances of a child class.我想为子类实例中的继承属性分配不同的值。 The code I use is我使用的代码是

class Parent:
    def __init__(self, n=50):
        # there are multiple parent attributes like 'n'
        # I use just one to reproduce the error
        self.n = n
        
    def print_n(self):
        print('n =', self.n)
        
class Child(Parent):
    def __init__(self, a=5):
        self.a = a
        
    def print_a(self):
        print('a =', self.a)
      
son1 = Child(n=100)
son1.print_n() 

The error message is错误信息是

son1 = Child(n=100)

TypeError: __init__() got an unexpected keyword argument 'n'

What would be the correct way to achieve the objective?实现目标的正确方法是什么?

I tried to put super().我试着把super(). init () in the init method of the child class according to the answer to this similar question, but it didn't work.根据this similar question的答案,在子类的init方法中的init () ,但它不起作用。

Your Child.__init__ needs to call Parent.__init__ explicitly;您的Child.__init__需要显式调用Parent.__init__ it won't happen automagically.它不会自动发生。 If you don't want Child.__init__ to have to "know" what Parent.__init__ 's args are, use *args or in this case **kwargs to pass through any kwargs that aren't handled by Child.__init__ .如果您不希望Child.__init__必须“知道” Parent.__init__的 args 是什么,请使用*args或在这种情况下使用**kwargs来传递任何未被Child.__init__处理的 kwargs。

class Parent:
    def __init__(self, n=50):
        # there are multiple parent attributes like 'n'
        # I use just one to reproduce the error
        self.n = n
        
    def print_n(self):
        print('n =', self.n)
        
class Child(Parent):
    def __init__(self, a=5, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.a = a
        
    def print_a(self):
        print('a =', self.a)
      
son1 = Child(n=100)
son1.print_n()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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