You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类代码运行无输出,面向对象编程新手求助

解决你的Python代码无输出问题

Hey there! I see exactly what's going on here—your code looks mostly right, but it's missing one crucial step that's keeping it from running the logic you wrote.

Let's break it down:

  • You've correctly defined the Player class with an __init__ constructor and a __str__ method to make the object printable.
  • You've also written a main() function that creates a Player instance and prints it.

The problem? You never actually call the main() function! In Python, defining a function doesn't make it run automatically—you have to explicitly tell Python to execute it.

Here's the fixed version of your code:

class Player:
    def __init__(self, health, damage):
        self.health = health
        self.damage = damage
    
    def __str__(self):
        return 'Total damage = '+str(self.damage)+' and total health = '+str(self.health)

def main():
    newPlayer = Player(10000, 3000)
    print(newPlayer)

# This line tells Python to run the main function when the script is executed directly
if __name__ == "__main__":
    main()

A quick explanation of that last part:

The if __name__ == "__main__": check is a standard Python pattern. It ensures that the main() function only runs when you execute this script directly (like through the terminal or IDLE). If you ever import this script into another Python file, the main() function won't run automatically, which is usually what you want.

Alternatively, you could just add a simple main() line at the end if you don't need that safeguard, but the if __name__ == "__main__": approach is better practice for reusable code.

Give this modified code a run, and you should see the output you expect: Total damage = 3000 and total health = 10000.

内容的提问来源于stack exchange,提问作者MAG314

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:40:32