在python中打印对象/实例名称 [英] print object/instance name in python

查看:355
本文介绍了在python中打印对象/实例名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有办法将 python 中的对象名称打印为字符串.例如,我希望能够说 ENEMY1 还剩 2 hp 或 ENEMY2 还剩 4 hp.有没有办法做到这一点?\

I was wondering if there is a way to print the object name in python as a string. For example I want to be able to say ENEMY1 has 2 hp left or ENEMY2 has 4 hp left. Is there a way of doing that?\

class badguy:
    def __init__(self):
        self.hp = 4

    def attack(self):
        print("hit")
        self.hp -= 1

    def still_alive(self):
        if self.hp <=0:
            print("enemy destroyed")
        else :
            print (str(self.hp) + " hp left")

    # creating objects

    enemy1 = badguy()
    enemy2 = badguy()

    enemy1.attack()
    enemy1.attack()
    enemy1.still_alive()
    enemy2.still_alive()

推荐答案

你必须先给他们起名字.例如

You'd have to first give them names. E.g.

class badguy:
    def __init__(self, name):
        self.hp = 4
        self.name = name

    def attack(self):
        print("hit")
        self.hp -= 1

    def still_alive(self):
        if self.hp <=0:
            print("enemy destroyed")
        else :
            print (self.name + " has " + str(self.hp) + " hp left")

    # creating objects

    enemy1 = badguy('ENEMY1')
    enemy2 = badguy('ENEMY2')

    enemy1.attack()
    enemy1.attack()
    enemy1.still_alive()
    enemy2.still_alive()

这篇关于在python中打印对象/实例名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆