I have just recently started to code at my school and I am learning how to use Python. Our teacher gave us this task:
Here are my codes:
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)
However, I got the following Error:
TypeError: __init__() takes 0 positional arguments but 1 was given
I added (self)
to __init__
as described in the comments, and now when I run the module the inputs work but after I put the inputs of name, order, quantity, and address, the outcome came out like this:
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
The Python "TypeError: takes 0 positional arguments but 1 was given" occurs for multiple reasons: Forgetting to specify the self argument in a class method. Forgetting to specify an argument in a function. Passing an argument to a function that doesn't take any arguments. Overriding a built-in function by mistake.
To solve this ” Typeerror: takes 1 positional argument but 2 were given ” is by adding self argument for each method inside the class. It will remove the error.
Using Positional Arguments Followed by Keyword Arguments One method is to simply do what the error states and specify all positional arguments before our keyword arguments! Here, we use the positional argument 1 followed by the keyword argument num2=2 which fixes the error.
The __init__
method needs to accept self
in Python, because, well, it's a method.
Change:
def __init__ ():
To:
def __init__ (self):
I don't want to provide the exact code for you, since this is homework, and you'll learn better if you arrive at the correct code yourself. I will point out the two main points (after adding self
, which has already been mentioned and you have added) that should allow you to proceed with writing the code yourself:
theName
inside of the function. That is looking for essentially a global variable, which should rarely, if ever, be used.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With