Home > Software engineering >  Why is it not printing a string when i call a class method
Why is it not printing a string when i call a class method

Time:03-02

Im just playing around with python OOP, and when I call this class method I get <__main__.User object at 0x7fb889516220>

code

 class User:
  users = []

  def __init__(self, name):
    self.name = name
    self.users.append(self)

  @classmethod
  def num_user(cls):
    return len(cls.users)

  @classmethod
  def viewUsers(cls):
    print(f"Number of users: {len(cls.users)}")
    for user in cls.users:
      print("\t- ", user)

  @staticmethod
  def isAllowed(age):
    return age >= 10

name = input("Enter your name: ")
age = int(input("Enter your age: "))

if User.isAllowed(age) == False:
  print(f"Sorry, {name.title()}. \nYou must be 10 or above to enter!\n")
    

else:
  print(f"Welcome, {name.title()}!\n")
    
  User(name).viewUsers()

I want it to print the names of the users. How could I fix this?

CodePudding user response:

This is a very minor bug. You were appending User objects to users but in the viewUsers method you wanted to print their names. Simply replace printing the user with user.name. The updated code is below.

class User:
    users = []

    def __init__(self, name):
        self.name = name
        self.users.append(self)

    @classmethod
    def num_user(cls):
        return len(cls.users)

    @classmethod
    def viewUsers(cls):
        print(f"Number of users: {len(cls.users)}")
        for user in cls.users:
            print("\t- ", user.name)

    @staticmethod
    def isAllowed(age):
        return age >= 10

name = input("Enter your name: ")
age = int(input("Enter your age: "))

if User.isAllowed(age) == False:
    print(f"Sorry, {name.title()}. \nYou must be 10 or above to enter!\n")
else:
    print(f"Welcome, {name.title()}!\n")

User(name).viewUsers()

CodePudding user response:

This can be fixed by slightly changing your viewUsers function. Currently, it is printing the User object instead make it print the name

  @classmethod
  def viewUsers(cls):
    print(f"Number of users: {len(cls.users)}")
    for user in cls.users:
      print("\t- ", user.name)
  • Related