I am trying to avoid using global, instead I created a class. I am having trouble calling the class, instead, I am getting the following error
TypeError: phone.__init__() missing 1 required positional argument: 'NUMBER_INPUT'
Any ideas? Thanks in advance!
class phone:
def __init__(self,NUMBER_INPUT):
self.NUMBER_INPUT = NUMBER_INPUT
def phone_number(self):
"""validate user input of phone number"""
while True:
self.NUMBER_INPUT = input("Please enter your phone number: ")
if re.fullmatch(r"\d{3}-\d{3}-\d{4}" ,self.NUMBER_INPUT):
print("You phone number is: " + self.NUMBER_INPUT)
break
print("Please enter a valid phone number ex. 123-456-5678")
phone().phone_number()
So, I think you neither did read documentation nor watched/read any tutorial about Python classes. So I will explain it here for you.
Class is a "object project". It may have predefined methods, predefined values. It also may have a way to construct these dynamically.
Class object at first need to be instantiated and then initiated. That means that firstly you need to create an instance of a class, then to initiate default values.
Python has 2 methods for this.
__new__() creates a new instance of a class and returns it. It's already realised for every Python class, but there may be special cases for you to override it.
__init__(*args, **kwargs) initiates values of a class. You must define non-static values here or globally in class.
So, creating a class object is achieved in python by calling class like this
A_instance = A(*args, **kwargs)
That in words means create me instance of A with these args and kwargs
So in your code, you are using (actualy overriding) __init__(*args, **kwargs) with args = (NUMBER_INPUT,) and kwargs = None.
Thus you must provide NUMBER_INPUT every time you create an object of phone, like so:
phone1 = phone("123-456-7890")
phone2 = phone("098-765-4321")
You must provide a value for NUMBER_INPUT when calling phone() like phone("123").phone_number().
But it would be better if you will use dummy value for NUMBER_INPUT in constructor like:
class phone:
def __init__(self):
self.NUMBER_INPUT = ""
def phone_number(self):
"""validate user input of phone number"""
while True:
self.NUMBER_INPUT = input("Please enter your phone number: ")
if re.fullmatch(r"\d{3}-\d{3}-\d{4}" ,self.NUMBER_INPUT):
print("You phone number is: " + self.NUMBER_INPUT)
break
print("Please enter a valid phone number ex. 123-456-5678")
phone().phone_number()
Related
I know this is not hard, but I keep getting either an undefined error or different errors, I tried everything I could think of to get the solution. I placed the input variables outside of the code and it worked partially. I'm only 3 weeks or so into my first computer science class. help is appreciated, please & thanks.
# function that prompts the user for a name and returns it
def user():
name = input("Please enter your name: ")
return name
# function that receives the user's name as a parameter, and prompts the user for an age and returns it
def userAge(name):
age = input("How old are you, {}? ".format(name))
return age
# function that receives the user's name and age as parameters and displays the final output
def finalOutput(name, age):
age2x = int(age) * 2
print("Hi, {}. You are {} years old. Twice your age is {}.").format(name, age, str(age2x))
###############################################
# MAIN PART OF THE PROGRAM
# implement the main part of your program below
# comments have been added to assist you
###############################################
# get the user's name
user()
# get the user's age
userAge("name")
# display the final output
finalOutput("name", "age")
You're not storing the values the user supplies, or passing them back to your function calls, here:
user()
userAge("name")
finalOutput("name", "age")
Change the above lines to:
name = user()
age = userAge(name)
finalOutput(name,age)
Correction 1:
Don't pass arguments with double quotes, that means you are passing a string literal to the function not actual value of variable.
for example, if you assign variable name as "Jhon" and you pass it to the function as userAge("name") means you are passing string literal "name" to userAge() not variable value "Jhon".
def printName(name):
print(name)
name = "jhon"
printName("name")
output: name
def printName(name):
print(name)
name = "jhon"
printName(name)
output: jhon
Better assign the return value to some Valerie and pass without double quotes as mentioned by #TBurgis.
Correction 2:
Syntax mistake in print statement. Correct syntax should be
print("Hi, {}. You are {} years old. Twice your age is {}.".format(name, age, str(age2x)))
I have a method object with assigned value from user's input inside a class. The problem is i can't use the method object maxcount_inventory = int(input("How many Inventories: ")) outside the class. The error says "method' object cannot be interpreted as an integer"
class CLASS_INVENTORY:
maxcount_inventory = int(input("How many Inventories: "))
inventory_name = []
def __init__(Function_Inventory):
for count_inventory in range(Function_Inventory.maxcount_inventory):
add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1)))
Function_Inventory.inventory_name.append(add_inventory)
def Return_Inventory(Function_Inventory):
return Function_Inventory.inventory_name
def Return_Maxcount(Function_Inventory):
return maxcount_inventory
maxcount_inventory = CLASS_INVENTORY().Return_Maxcount
Another extra question if I may, how can i access items in the list per index outside the class? I have the code below, but I think it's not working. Haven't found out yet due to my error above.
for count_inventory in range(maxcount_inventory):
class_inv = CLASS_INVENTORY().Return_Inventory[count_inventory]
print(class_inv)
skip()
Here is my full code: https://pastebin.com/crnayXYy
Here you go I've refactored your code.
As #Daniel Roseman mentioned you should be using self rather than Function_Inventory, so I changed that. I also changed the return value of Return_Maxcount to provide a list as you requested.
class CLASS_INVENTORY:
maxcount_inventory = int(input("How many Inventories: "))
inventory_name = []
def __init__(self):
for count_inventory in range(self.maxcount_inventory):
add_inventory = str(input("Enter Inventory #%d: " % (count_inventory+1)))
self.inventory_name.append(add_inventory)
def Return_Inventory(self):
for item in self.inventory_name:
print(item)
def Return_Maxcount(self):
return self.inventory_name
maxcount_inventory = CLASS_INVENTORY()
inventory_list = maxcount_inventory.Return_Maxcount()
maxcount_inventory.Return_Inventory()
You can change the print statement at the bottom and set that equal to a variable to access it outside of the class itself.
In your code just change this:
maxcount_inventory = CLASS_INVENTORY().Return_Maxcount
to this:
maxcount_inventory = CLASS_INVENTORY().Return_Maxcount()
also change the variables in your class to have the self. prefix before them
like self.maxcount_inventory
the reason is you want to call your method , otherwise it will try getting a variable not the method.
you also want to change all your arguments in your functions inside of the class to self
UPDATE
Tells me that TypeError: __init__() missing 1 required positional argument: 'storlek'
My class
class Hanterare:
def __init__(self, storlek):
self.storlek =storlek
My functions
def fråga_storlek():
try:
Hanterare().storlek =int(input('Choose size'))
except ValueError:
print("Wrong try again!!")
fråga_storlek()
And I want to use the value, the user has chosen and call them into my other functions for example:
def getNewBoard():
board = []
for i in range(fråga_storlek()):
board.append([' '] * fråga_storlek())
Unless I'm missing a notation, Q is a terrible name. Variable and method names should be in lowercase, and describe the purpose of the variable. board_width would be a much better name.
Having a method with the same name as a class member is confusing. Since you're asking for the board size, I'd rename the method to something like ask_board_size.
After taking the above into consideration, the problem solves itself:
class BoardHandler(self, board_size):
self.board_size = board_size
def ask_board_size(self):
try:
self.board_size = int(input("Choose size please"))
except ValueError:
print("Wrong try again!")
ask_board_size()
And is that constructor a new notation? It should probably use __init__:
class BoardHandler:
def __init__(self, board_size):
self.board_size = board_size
...
No, to create a field in a class, you should declare it in a function called __init__(self). Like so:
class BoardHandler:
def __init__(self, Q):
self.Q = Q
You can also take input upon creation instead of having it as a parameter, like so:
class BoardHandler:
def __init__(self):
self.Q = int(input("What size would you prefer?"))
You don't want to use:
class BoardHandler:
self.Q = 5 #some number
unless you want the board size to be the same across all BoardHandlers.
Then you can access it in other methods of the class by just using self.Q.
To use it outside the class, here's how:
b_size = int(input("What size?"))
bh = BoardHandler(b_size)
print("The board size is: " + str(bh.Q))
I have to write a program to demonstrate a customer using their credit card to check out, I have spent a few hours trying to figure out how to do it and have provided my code below.
I have to make a class, then use it in a main function.
This is what I have so far:
class Customer:
def __init__(self, customer_name, credit_card_num, credit_security_code, debit_card_num, debit_pin):
self.customer_name = name
self.credit_card_num = credit_num
self.credit_security_code = credit_code
self.debit_card_num = debit_num
self.debit_pin = debit_pin
def inputCardInfo(self):
self.customer_name = str(input("Enter your name: "))
self.credit_card_num = str(input("Enter credit card Number: "))
self.credit_security_code = str(input("Enter 3-digit security code: "))
self.debit_card_num = str(input("Enter debit card number: "))
self.debit_pin = str(input("Enter 4-digit PIN: "))
then the main function:
from customer import Customer
def main():
print("Welcome to Wake-Mart. Please register.")
customer_name = input("enter name: ")
customer1 = Customer(customer_name)
print("Registration completed")
main()
I don't know the correct way to call the class methods. I feel if I can figure out how to make one of these work I can figure out the rest.
If you want to understand behaviors and properties more deeply I would recommend making a separate behavior for each value. (get_credit_num, get_debit_num, etc.)
Then, in your main, just call each function individually to get each value.
And to clarify, "class functions", or behaviors, are just things an object can do. You call them the same way you would any function, with the only difference being you put the name of the instance you are calling this behavior for before the function to replace "self". So if you were calling "InputCardInfo" for the object customer1, you would do it like so:
customer1.InputCardInfo(other parameters)
Your code as-is will not work because you are not passing all required parameters when initializing your class.
customer1 = Customer(customer_name)
All of the additional parameters besides self included in your def __init__(self, var1, var2, var3): needs to be passed to the class instance when initializing. There are also variable naming issues with your code but I hope my example below clarifies things for you.
A quick note first to help you better understand: self.customer_name = name does not make sense in your code because there is no parameter named name included in the __init__() method. You must associate an instance variable (self.whatever) to a known variable name passed in through the __init__(self, external_var) method so that self.whatever = external_var. Then, and only then, can you use class methods to call self.whatever and expect to receive the data you passed from external_var. Also, additional parameters you include after self in __init__(self, ..., ...) MUST be passed as variables when creating a class instance.
class Customer:
def __init__(self, customer_name, credit_card_num, credit_security_code, debit_card_num, debit_pin):
self.customer_name = customer_name
self.credit_card_num = credit_card_num
self.credit_security_code = credit_security_code
self.debit_card_num = debit_card_num
self.debit_pin = debit_pin
name = 'Mike'
cc_num = '0000 0000 0000 0000'
code = '111'
debit_num = '1111 1111 1111 1111'
pin = '1234'
new_customer = Customer(name, cc_num, code, debit_num, pin)
![enter image description here][1]i am creating two classes student(base) and detail .Detail is inheriting all the attributes of base .I am initializing the attributes (roll_no,name and class_stud)subclasses of base with students object of subclass created with student.subclasses().Here is the code:
student=type('student',(object,),{})
def getinfo():
for studen in student.__subclasses__():
studen.roll_no=input("enter the roll number")
studen.name=input("enter the name of student")
studen.class_stud=input("enter the class")
def printinfo():
print('roll number ',roll_no,name,class_stud)
detail=type('detail',(student),{'info':getinfo(),'print':printinfo()})
ob=detail()
ob.info
ob.print
I have never seen anyone create Python classes this way, except to see if they could. You have quite a few errors, but this might do what you want (although that is not clear):
student=type('student',(object,),{})
def getinfo(self):
for studen in student.__subclasses__():
studen.roll_no=input("enter the roll number: ")
studen.name=input("enter the name of student: ")
studen.class_stud=input("enter the class: ")
def printinfo(self):
print('roll number ',self.roll_no,self.name,self.class_stud)
detail=type('detail',(student,),{'info':getinfo,'print':printinfo})
ob=detail()
ob.info()
ob.print()
As you can see, your main error was in not passing the object into the methods. Other errors included a missing comma after student when defining detail. See also comments by #abarnert.
This is a horrible way of defining a class in Python.
EDIT:
I have no idea why you are iterating over subclasses, this is probably what you meant for getinfo:
def getinfo(self):
self.roll_no=input("enter the roll number: ")
self.name=input("enter the name of student: ")
self.class_stud=input("enter the class: ")