我是python的新手,我正在尝试创建一个基本的python计算器
#!/usr/bin/env python
class Calculator:
def __int__(self,x,y):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def sub(self):
return self.x - self.y
def multi(self):
return self.x * self.y
def div(self):
return self.x / self.y
def convert(self,a,b):
try:
int_a = int(a)
int_b = int(b)
except ValueError:
int_a = float(a)
int_b = float(b)
return int_a,int_b
run = True
while run:
print "Please choose what you'd like to do:"
print "0: Addition"
print "1: Subtraction"
print "2: Multiplication"
print "3: Division"
print "4: Quit Application"
choice = raw_input()
if choice == "0":
str_a = raw_input("Enter 1st number : ")
str_b = raw_input("Enter 2nd number : ")
c = Calculator(str_a,str_b)
c.add()
但我收到如下错误:
c = Calculator(str_a,str_b)
TypeError: this constructor takes no arguments
请有人帮我解决这个问题
答案 0 :(得分:1)
这是我期待你需要的解决方案,
#!/usr/bin/env python
class Calculator:
def __init__(self,x,y):
self.x = int(x)
self.y = int(y)
def add(self):
return self.x + self.y
def sub(self):
return self.x - self.y
def multi(self):
return self.x * self.y
def div(self):
return self.x / self.y
def convert(self,a,b):
try:
int_a = int(a)
int_b = int(b)
except ValueError:
int_a = float(a)
int_b = float(b)
return int_a,int_b
run = True
while run:
print "Please choose what you'd like to do:"
print "0: Addition"
print "1: Subtraction"
print "2: Multiplication"
print "3: Division"
print "4: Quit Application"
choice = raw_input()
if choice == "0":
str_a = raw_input("Enter 1st number : ")
str_b = raw_input("Enter 2nd number : ")
c = Calculator(str_a,str_b)
print c.add()
答案 1 :(得分:-1)
请使用input
代替raw_input
str_a = input("Enter 1st number : ")
str_b = input("Enter 2nd number : ")
raw_input
默认采用字符串。