代码之家  ›  专栏  ›  技术社区  ›  Ninja Warrior 11

python:实例的返回值[重复]

  •  0
  • Ninja Warrior 11  · 技术社区  · 6 年前

    这个问题已经有了答案:

    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 回复  |  直到 6 年前
        1
  •  3
  •   Md Johirul Islam    6 年前

    您需要实现 __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

        2
  •  1
  •   Cam    6 年前

    我想你在找 __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