Home > Blockchain >  TypeError: str() argument 2 must be str, not tuple when trying to print out a class name and attribu
TypeError: str() argument 2 must be str, not tuple when trying to print out a class name and attribu

Time:03-19

Create a program called classname.py.

The program should define:

  • A class called person that has one method called hello
  • One attribute called name, which represents the name of the person

The hello method should print the string to the screen:

‘My name is ____ and I am a _____’

where:

  • The first blank should be the name attribute
  • The second blank should be the name of the class
  • The above blanks should NOT be manually printed

After defining the class, there are three things you must do:

  • Instantiate an object of the class
  • Run the hello method of the instantiated object
  • Print the name of the class

(The expected output is <class ‘main.person’>)

classname.py

import sys

class Classmate(str(sys.argv[1])):
    def __init___(self, name):
        self.name = name

    def hello(self):
        print(f'My name is {self.name} and I am a', end = '')

classmate1 = Classmate(sys.argv[1])
classmate1.hello()
print(classmate1.__class__)

Test Case Examples:

python3 classname.py Obi-Wan
python3 classname.py 'Ronald Jenkees'
python3 classname.py 123 

Example Expected Output:

My name is Ronald Jenkees and I am a person
<class '__main__.person'>

Error Message:

Traceback (most recent call last):
  File "classname.py", line 3, in <module>
    class Classmate(str(sys.argv[1])):
TypeError: str() argument 2 must be str, not tuple

CodePudding user response:

The problem is that you misspelled __init__. I couldn't tell until I copied your code into an editor.

import sys

class Classmate:
    def __init__(self, name):
        self.name = name

    def hello(self):
        print(f'My name is {self.name} and I am a', end = '')

classmate1 = Classmate(sys.argv[1])
classmate1.hello()
print(classmate1.__class__)

When I try this on my machine with __init__ spelled correctly, I see:

My name is Frank and I am a<class '__main__.Classmate'>

Which is exactly what you've told it to type.

  • Related