Python:返回实例的值

时间:2018-05-27 05:05:21

标签: python

这是一个基本问题,可能会将此标记为重复。在过去的几天里,我学习了中级Python,但是我忘了记住类的特殊方法来获取类的值。

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

2 个答案:

答案 0 :(得分:3)

您需要按以下方式实施__str__(self)方法:

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

工作Ideone https://ideone.com/D48pwl

答案 1 :(得分:1)

我认为你正在寻找__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