各位大大好,我寫了一個程式,但就不知道為甚麼會出錯
class Calc:
def plus(self, a, b):
return a + b
def minus(self, a, b):
return a - b
a = Calc.plus(1, 2)
b = Calc.minus(2, 1)
print(a)
print(b)
然後有Error
File "c:\Users\ericc\Downloads\python程式\Calc.py", line 6, in <module>
a = Calc.plus(1, 2)
TypeError: plus() missing 1 required positional argument: 'b'
我改成了這樣
class Calc:
def plus(self, a, b):
self.a = a
self.b = b
return self.a + self.b
def minus(self, a, b):
self.a = a
self.b = b
return self.a - self.b
a = Calc.plus(1, 2)
b = Calc.minus(2, 1)
print(a)
print(b)
Error變成了
File "c:\Users\ericc\Downloads\python程式\Calc.py", line 14
self.b = b
^
TabError: inconsistent use of tabs and spaces in indentation
真的救命
求幫忙
這是你要的?
code
class Calc:
def __init__(self, a, b):
self.a = a
self.b = b
def plus(self):
return self.a + self.b
def minus(self):
return self.a - self.b
Calc(3, 2).plus() # return 5
Calc(3, 2).minus() # return 1
也可以試試用靜態方法(static method)的方式來寫
希望有幫助到你
class Calc:
@staticmethod
def plus(a, b):
return a + b
@staticmethod
def minus(a, b):
return a - b
a = Calc.plus(1, 2)
b = Calc.minus(2, 1)
print(a)
print(b)