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()
CodePudding user response:
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")
CodePudding user response:
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()