Home > Back-end >  <__main__.myClass object at 0x000001CCDC46BD90> instead of expected string output
<__main__.myClass object at 0x000001CCDC46BD90> instead of expected string output

Time:04-07

Write a Python class which has two methods get_String and print_String. get_String should accept a string from the user and print_String should print the string in upper case.

My Code:

class myClass():
    def __init__(self, userInput = input("What is your name? ")):
        self.userInput = userInput
    def get_string(userInput):
        return userInput
    def print_string(userInput):
        output = userInput.upper()
        return output
print(myClass())
Terminal:
What is your name? Anthony
<__main__.myClass object at 0x000001CCDC46BD90>

Should have come out as:

ANTHONY

CodePudding user response:

Hi you can rearrange your code a bit so that the methods read the input and then print it out in the required format:

class myClass():
    def __init__(self):
        self.userInput = None
    def get_String(self):
        self.userInput = input('What is your name? ')
    def print_String(self):
        print(self.userInput.upper())

# Instantiate the object
x = myClass()

# Read the name
x.get_String()

# Print the name
x.print_String()

# This prints:
#
# What is your name? Anthony
# ANTHONY

CodePudding user response:

Just modify your print_string method by passing the self argument and then call with the print_string() method.

class myClass():
    def __init__(self, userInput = input("What is your name? ")):
        self.userInput = userInput
    def print_string(self):
        output = self.userInput.upper()
        return output
print(myClass().print_string())

CodePudding user response:

You seem to be missing the fundamentals re: classes in Python:

  1. The assignment asks you to get the string using the get_string method, not during __init__.
  2. Your print_string should print the stored string, it shouldn't require the user to pass a new string.
  3. You are not attempting to convert the string to uppercase anywhere in your code.

Here is an improved version:

class MyClass:
    def __init__(self):
        self.name = None

    def get_string(self):
        self.name = input("What is your name? ")

    def print_string(self):
        print(self.name.upper())


my_object = MyClass()
my_object.get_string()
my_object.print_string()
  • Related