最终结果中的问题(Python)

2024-04-29 12:37:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的初学者,我正在开发一个计算器,创建一个类,其中有4个函数,即4个操作。而且主要只有基本的条目。我在这个项目中的目标是使用最小数量的“如果”。 有没有办法做到这一点? 但是,这给了我一个错误,我无法想象它是如何发生的,可能是在脸上,但我来这里是想请你帮忙

main.py
from calc import *
numero1 = int(input('Digite um numero: '))
sinal = input('Digite a operação: ')
numero2 = int(input('Digite outro numero: '))
retornaValor = 0
retornaValor = Calculadora
print(retornaValor)




calc.py
class Calculadora:

def __init__(self,numero1,numero2):
    self.a = numero1
    self.b = numero2

def soma(self,numero1,numero2):
    soma = self.a + self.b
    print('Resultado: ',soma)

def subtrai(self,numero1,numero2):
    subtrai = self.a - self.b
    print('Resultado: ',subtrai)

def divisao(self,numero1,numero2):
    divisao = self.a / self.b
    print('Resultado: ',divisao)
    
def multiplica(self,numero1,numero2):
    multiplica = self.a * self.b
    print('Resultado: ',multiplica)

Console: 

Digite um numero: 100
Digite a operação: +
Digite outro numero: 30
''<class 'calc.Calculadora'>'' (????)

它不会带来结果


Tags: selfinputdefcalccalculadoraprintsomanumero1
2条回答

在主文件中

  • 您必须创建一个参数为1和2的对象,如下所示:my_object_cal = Calculadora(number1,number2)
  • 然后,使用if/elif/else调用基于符号(*+-/)的右函数,如下所示:
    if  sign =="+" :
        my_object_cal.soma(number1, number2)
    elif sign == "-" :
        my_object_cal.subtrai(number1, number2)
    elif ...
    else ...

你可以参考this tutorial on if,elif,else

你还必须学习how to create and instantiate object in python

之后,您可以在using static methods中前进

祝你好运

我不确定你到底在找什么,但你有几个问题要解决。我可能遗漏了一些东西,但是您需要实例化您的类,以便发生任何事情,并且在执行此操作时,您需要为init函数提供参数。我还建议您合并一些if/else或try/except语句,以捕获用户提供的输入无法转换为int()的情况。考虑到这一点,下面是一个非常简单的工作示例:

#get user input (plug for if/else)
numero1 = int(input('Digite um numero: '))
sinal = input('Digite a operação: ')
numero2 = int(input('Digite outro numero: '))


class Calculadora(): #class needs to be defined with ()

    def __init__(self,numero1,numero2): #make sure to supply args here with self 
        self.numero1 = numero1
        self.numero2 = numero2

    def soma(self): #you don't need to supply the input args again if you've already declared above
        soma = self.numero1 + self.numero2
        print('Resultado: ',soma)

    def subtrai(self):
        subtrai = self.numero1 - self.numero2
        print('Resultado: ',subtrai)

    def divisao(self):
        divisao = self.numero1 / self.numero2
        print('Resultado: ',divisao)
        
    def multiplica(self):
        multiplica = self.numero1 * self.numero2
        print('Resultado: ',multiplica)


example = Calculadora(numero1,numero2) #instantiate the class with supplied args
print(example.subtrai()) #call the function you want from inside the class

不确定这是否是您想要的,但如果需要,可以轻松调整为不同的格式或稍微不同的运行方式。祝你好运

相关问题 更多 >