【问题标题】:Don't understand cause of this TypeError in subclass definition [closed]不了解子类定义中此 TypeError 的原因 [关闭]
【发布时间】:2021-06-01 15:49:34
【问题描述】:

描述代码和错误如下:

代码-

#Inheritance

class Father:
    def __init__(self,home):
        self.home = home

class Son(Father):
    def __init__(self,wife,bike):
        super(). __init__(self,home)
        self.wife = wife
        self.bike = bike
        
sonworth = Son("fourbhk","nikita","hayabusa")
print(sonworth.home,sonworth.wife,sonworth.bike)

错误 -

TypeError                                 Traceback (most recent call last)
<ipython-input-69-b4fa474bd6de> in <module>
     10         self.bike = bike
     11 
---> 12 sonworth = Son("fourbhk","nikita","hayabusa")
     13 print(sonworth.home,sonworth.wife,sonworth.bike)
     14 

TypeError: __init__() takes 3 positional arguments but 4 were given

【问题讨论】:

    标签: python class oop inheritance


    【解决方案1】:

    我可以看到您错过了来自Son 的home 参数:

    class Father:
        def __init__(self, home):
            self.home = home
    
    class Son(Father):
        def __init__(self, home, wife, bike):
            super().__init__(home)
            self.wife = wife
            self.bike = bike
            
    sonworth = Son("fourbhk", "nikita", "hayabusa")
    print(sonworth.home, sonworth.wife, sonworth.bike)
    

    【讨论】:

      【解决方案2】:

      您忘记使用来自Son 的home 参数

      您也不需要使用Super() 函数,因为Father 不继承任何东西

      class Father:
          def __init__(self,home):
              self.home = home
      
      class Son(Father):
          def __init__(self,home,wife,bike):
              Father. __init__(self,home)
              self.wife = wife
              self.bike = bike
              
      sonworth = Son("fourbhk","nikita","hayabusa")
      print(sonworth.home,sonworth.wife,sonworth.bike)
      

      【讨论】:

      • 谢谢,老师告诉我要使用超级功能。
      • 顺便说一句,在这种情况下,您应该使用super(),以防此类更改为从不同的超类继承。那你就不用改__init__()里的代码了。
      猜你喜欢
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      相关资源
      最近更新 更多