I'm new to Python and trying create a program that defines a class called person that has one method called hello, and one attribute called name, which represents the name of the person. The hello method should print the following string to the screen:
‘My name is name attribute and I am a name of class’
1)Instantiate an object of the class, 2)Run the hello method of the instantiated object (e.g., John.hello()), 3) Use sys.argv
Here is my code:
import sys
class person():
def __init__(self,_name):
self.name=_name
_name = sys.argv[1]
def hello(self):
print (f"My name is {sys.argv[1]} I am a {self.__class__.__name__}")
p1 = person()
p1.hello()
def main():
p = person()
print (type(p))
if __name__ == "__main__":
main()
Example expected output:
My name is Obi-Wan and I am a person
<class '__main__.person'>
Actual output:
File "classname.py", line 10, in <module>
p1 = person()
TypeError: __init__() missing 1 required positional argument: '_name'
I don't know what I am doing wrong. Please help!
Your issue was that you've created a class which expects an argument, but then did not give it the requested argument.
Since the __init__
function requires the _name
argument, the initialization of the person
class must be done with a name, for example person('my_name')
.
Since you get the name as an input, you probably want to save it in the class and reuse it, instead of extracting it from sys.argv
every time. So the end result should look something like this-
import sys
class person():
def __init__(self, name):
self.name = name
def hello(self):
print(f"My name is {self.name} I am a {self.__class__.__name__}")
def main():
input_name = sys.argv[1]
p = person(input_name)
p.hello()
if __name__ == "__main__":
main()