【问题标题】:super() function in python [closed]python中的super()函数[关闭]
【发布时间】:2022-01-19 22:52:48
【问题描述】:

super() 函数有助于访问父类的方法和属性,但在下面的代码中,我们为父类的属性 (name) 分配一个值,并为子类的属性 (name, age ) 另一个值。但是我想在子类中访问父类的属性(name),而不更改值。我该怎么办?

class Parent:                    #Parent class
   def __init__(self,name):
       self.name=name
 
   def show(self):
       print(self.name)
 
class Child(Parent):              #child class
    def __init__(self,name,age):
        super().__init__(name)
        self.age=age
 
    def showName(self):
        print(self.name,self.age)
 
child=Child("nin",12)
parent=Parent("ninad")
child.showName()
parent.show()

输出-

nin 12
ninad

【问题讨论】:

  • 这是实例属性,它们不属于任何类,它们属于实例
  • 我真的不明白你在问什么,你期望的输出是什么?
  • 子类自动继承父类的所有属性。 ParentChild 没有单独的 name 属性。
  • 扩展@Barmar 的评论,它是具有属性的对象。该对象只有一个name。是父类初始化还是子类初始化无关紧要。
  • 所有属性都附加到绑定到self 的实例上,不管这样做的方法是在Parent 还是Child 中定义的。 Parent.__init__ 知道如何设置name 属性,所以Child.__init__ 不必这样做。

标签: python inheritance


【解决方案1】:

在代码中,我们为父母的属性(姓名)分配了一个不同的值,为孩子的属性(姓名,年龄)分配了一个不同的值

您正在为名为@9​​87654321@ 和parent实例分配不同的值,是的,但是相同实例中,属性是相同的值。

我想在不更改值的情况下访问子类中父级的属性(名称)。我该怎么办?

你已经做到了。 Child 类函数中的self.name 引用 Parent 类的属性,因为它是继承的。

【讨论】:

    【解决方案2】:

    使用super() 的推荐方法是将参数作为关键字 参数提供,这样Child.__init__ 不仅将name 属性的定义推迟到Parent.__init__,它不会'甚至不需要知道属性存在

    class Parent:
       def __init__(self, *, name, **kwargs):
           super().__init__(**kwargs)
           self.name = name
     
       def show(self):
           print(self.name)
     
    
    class Child(Parent):
        def __init__(self, *, age, **kwargs):
            super().__init__(**kwargs)
            self.age = age
     
        def showName(self):
            print(self.name, self.age)
    
    
    child = Child(name="nin", age=12)
    # Child.__init__ calls super().__init__, which resolves to Parent.__init__
    # Parent.__init__ sets the name attribute on the object
    # Child.__init__ sets the age attribute on the object
    assert child.name == "nin"
    assert child.age == 12
    

    注意superParent.__init__ 中的使用。仅仅因为Parent 没有从除object 之外的任何类继承,并不意味着从Parent(直接或间接)继承的某个其他类在Parent 和@ 之间不会有一个或多个类987654332@ 在其方法解析顺序中。考虑:

    class Something:
        ...
    
    class MadeupExample(Parent, Something):
        def __init__(self, *, x, **kwargs):
            super().__init__(**kwargs)
    

    当您调用MadeupExample(name="bob", x=3) 时,Parent.__init__ 中对super().__init__ 的调用指的是Something.__init__,而不是object.__init__

    【讨论】:

      猜你喜欢
      • 2011-09-15
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多