英文:
What is the right way to implement addition using class in Python and avoid TypeError with missing positional argument?
问题
TypeError: Add.add() 缺少一个必需的位置参数:'b'。
英文:
class Add:
    def __init__(self,a,b):
        self.a = a
        self.b = b
    def add(a,b):
       return self.a + self.b
obj = Add(3,4)
print(obj.add())
Error message:
print(obj.add())
          ^^^^^^^^^
TypeError: Add.add() missing 1 required positional argument: 'b'
答案1
得分: 0
只应将self作为参数传递。其他值在实例本身上访问。
def add(self):
   return self.a + self.b
英文:
You should only take self as a parameter. The other values are accessed on the instance itself.
def add(self):
   return self.a + self.b
答案2
得分: 0
class Add:
	def __init__(self,a,b):
		self.a = a
		self.b = b
	def add(self):
		return self.a + self.b
obj = Add(3,4)
print(obj.add())
英文:
class Add:
	def __init__(self,a,b):
		self.a = a
		self.b = b
	def add(self):
		return self.a + self.b
obj = Add(3,4)
print(obj.add())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论