【问题标题】:How to change the variable of Parent Class from a Child Class (in Python)? [duplicate]如何从子类(在 Python 中)更改父类的变量? [复制]
【发布时间】:2021-10-03 06:16:26
【问题描述】:

在 python 中实践继承

我在 python 上练习继承。我不确定如何更改父类的变量名。

# Parent Class
class Family_Member():
    def __init__(self, name):
        self.name = name
    def catch_phrase(self):
        print("I am a family member")
# Child Class
class Mum(Family_Member):
    def __init__(self):
        Family_Member.__init__(self)
# Attempting to change variable of parent class from child class
My_Mum = Mum("Kerry")

这给了我

TypeError: __init__() takes 1 positional argument but 2 were given

问题

  1. 为什么会发生这种情况?如何命名我的成员 Kerry 而不会出现此错误

  2. 为什么我在子类中不包含init函数时不会出现这个错误。例如,此代码有效

    # Attempt 2
    class Family_Member():
         def __init__(self, name):
             self.name = name
         def catch_phrase(self):
             print("I am a family member")
     class Mum(Family_Member): # THIS CLASS IS NOW EMPTY
        pass
      My_Mum = Mum("Kerry")
         print(My_Mum.name)
    

【问题讨论】:

  • Mum. __init__ 不“知道”Family_Member.__init__ 收到 name。它尤其不“知道”它必须接收并传递name

标签: python class object inheritance init


【解决方案1】:
class Family_Member():
    def __init__(self, name):
        self.name = name
    def catch_phrase(self):
        print("I am a family member")
        
class Mum(Family_Member):
    def __init__(self, name):
        Family_Member.__init__(self, name)
        
My_Mum = Mum("Kerry")

应该可以吧?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    相关资源
    最近更新 更多