这是一个有效的多级继承程序。当我运行它时,它说“ AttributeError:类型对象'starts'没有属性'math'”。我检查了类的关联,并继承了它们。我是一个初学者,因此它将对我的前进有很大帮助。
class starts:
def __init__(self, ans, a, b):
self.ans = input("Please type the operation to do the function as below \n 1. Sum \n 2. Subtract \n 3. multiply \n 4. divide \n")
self.a = int(input("please enter the number you want to do the operation with : "))
self.b = int(input("please enter the number you want to do the operation with : "))
class maths(starts):
def __init__(self, sum, subtract, divide, multiply):
self.sum = sum
self.subtract = subtract
self.divide = divide
self.multiply = multiply
def sum(self, a, b):
print (self.a + self.b)
#
def subtract(self, a, b):
print(self.a - self.b)
#
def divide(self, a, b):
print(self.a / self.b)
#
def multiply(self, a, b):
print(self.a * self.b)
class operations(maths):
def __init__(self, class_a):
#super(operations,self).__init__(self.ans, self.a, self.b)
super().__init__(self.ans, self.a, self.b)
self.ans = class_a.ans
if class_a.ans == self.sum:
print(starts.maths.sum(self.a, self.b))
elif class_a.ans == self.subtract:
print(starts.maths.subtract(self.a, self.b))
elif class_a.ans == self.divide:
print(starts.maths.divide(self.a, self.b))
else:
class_a.ans == self.multiply
print(starts.maths.multiply(self.a, self.b))
starts.maths.operations()
答案 0 :(得分:0)
您的operations
类继承了maths
类,后者继承了starts
类,因此可以使用父类的__init__
方法初始化的所有实例变量子类(如果您只是调用super().__init__()
:
class starts:
def __init__(self):
self.ans = input("Please type the operation to do the function as below \n 1. Sum \n 2. Subtract \n 3. multiply \n 4. divide \n")
self.a = int(input("please enter the number you want to do the operation with : "))
self.b = int(input("please enter the number you want to do the operation with : "))
class maths(starts):
def __init__(self):
super().__init__()
def sum(self, a, b):
return (self.a + self.b)
def subtract(self, a, b):
return(self.a - self.b)
def divide(self, a, b):
return(self.a / self.b)
def multiply(self, a, b):
return(self.a * self.b)
class operations(maths):
def __init__(self):
super().__init__()
if self.ans == 'sum':
print(self.sum(self.a, self.b))
elif self.ans == 'subtract':
print(self.subtract(self.a, self.b))
elif self.ans == 'divide':
print(self.divide(self.a, self.b))
elif self.ans == 'multiply':
print(self.multiply(self.a, self.b))
else:
print('Unknown operation: %s' % self.ans)
operations()
样本输入和输出:
Please type the operation to do the function as below
1. Sum
2. Subtract
3. multiply
4. divide
sum
please enter the number you want to do the operation with : 3
please enter the number you want to do the operation with : 7
10