我刚刚开始在我的学校编写代码,我正在学习如何使用Python。 我们的老师给了我们这个任务:
以下是我的代码:
class CustomerInfo:
def __init__ ():
self.name = theName
self.order = theOrder
self.quantity = theQuantity
self.address = theAddress
def setName( self, newName ):
self.Name = newName
def setOrder ( self, newModel ):
self.model = newModel
def setQuantity ( self, newQuantity ):
self.quantity = newQuantity
def setAddress (self, newAddress ):
self.address = newAddress
def getName ( self ):
return self.name
def getOrder ( self ):
return self.order
def getQuantity ( self ):
return self.quantity
def getAddress ( self ):
return self.address
name = input("Enter your name: ")
order = input("Enter your order: ")
quantity = int(input("Enter your quanity: "))
address = input("Enter your address: "))
customer1 = CustomerInfo()
print ( "Name: ", customer1.name)
print ( "Order: ", customer1.order)
print ( "Quanity: ", customer1.quantity)
print ( "Address: ", customer1.address)
但是,我收到以下错误:
TypeError: __init__() takes 0 positional arguments but 1 was given
我按照评论中的说明将(self)
添加到__init__
,现在当我运行模块时输入有效,但在我输入名称,顺序,数量和地址之后,结果出来是这样的:
Traceback (most recent call last):
File line 32, in <module>
customer1 = CustomerInfo()
File line 4, in __init__
self.name = theName
NameError: name 'theName' is not defined
答案 0 :(得分:14)
__init__
方法需要在Python中接受self
,因为,这是一种方法。
变化:
def __init__ ():
要:
def __init__ (self):
答案 1 :(得分:1)
我不想为您提供确切的代码,因为这是家庭作业,如果您自己获得正确的代码,您将会学得更好。我将指出两个要点(在添加self
之后,已经提到并且已经添加),这应该允许您继续自己编写代码:
theName
之类的内容。那本质上是在寻找一个全局变量,如果有的话,该变量应该很少使用。答案 2 :(得分:0)
是的,这是您忘记(self,...)
arg to __init__()
或任何其他方法时收到的消息。