繁体   English   中英

如何从父 class 构造函数中获取变量并在子 class 中使用它?

[英]How can I take the variable from the parent class constructor and use it in the child class?

我一直在研究预算项目中的类和对象。 我对如何从父 class 中的构造函数获取变量并在子 class 中使用它感到非常困惑。

这可能看起来像重复,但我无法理解其他帖子的答案。 请尽量简单地解释,不要使用任何“外国”术语,因为我是编码新手。

我遇到的主要问题是:

TypeError: __init__() takes 1 positional argument but 2 were given
TypeError: super() argument 1 must be type, not int

这是我的代码:

class budget:
    def __init__(self, money):
        self.money = money

class food(budget):
    def __init__(self, money):
        money = super(budget).__init__(2)
    def show(self):
        print('hi')

money = 50
a = food(money)
a.show()
#Option 1 ---> with your example you dint need an __init__
class budget:
    def __init__(self, money):
        self.money = money

class food(budget):
    def show(self):
        print('hi')
money = 50
a = food(money)
a.show()


#Option 2 if you still need to override the init
class budget:
    def __init__(self, money):
        print('here')
        self.money = money

class food(budget):
    def __init__(self, money):
        super().__init__(money)
    def show(self):
        print('hi')

money = 50
a = food(money)
a.show()

** 另请注意:您不能传入一个参数,然后变成一个变量

暂无
暂无

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

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