0

This is a basic question, might flag this as a duplicate. I am overloaded with information over the past few days studying Intermediate Python and I forgot to remember the special method of class to get the value of class.

class Example():

    def __init__(self):
        self.name = "Ninja Warrior"

    # add special method to return self.name as a default value of Example()

print(Example().name)
# Ninja Warrior

print(Example())  # This is what I want to do
# Ninja Warrior
Ninja Warrior 11
  • 362
  • 3
  • 17

2 Answers2

3

You need to implement the __str__(self) method as following:

class Example():

def __init__(self):
    self.name = "Ninja Warrior"

# add special method to return self.name as a default value of Example()
def __str__(self):
    return self.name

print(Example().name)
# Ninja Warrior

print(Example())  # This is what I want to do
# Ninja Warrior

Working Ideone https://ideone.com/D48pwl

Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56
1

I think you're looking for __str__

class Example():

    def __init__(self):
        self.name = "Ninja Warrior"

    def __str__(self):
        return self.name

    # add special method to return self.name as a default value of Example()

print(Example().name)
# Ninja Warrior

print(Example())  # This is what I want to do
# Ninja Warrior
Cam
  • 14,930
  • 16
  • 77
  • 128