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



我一直在预算项目中处理类和对象。我非常困惑如何将从父类中的构造函数获得的变量用于子类。

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

我得到的主要问题是:

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()

**另请注意:不能传入一个变为变量的参数

最新更新