我想知道是否有办法在python中将对象名称打印为字符串。例如,我想能够说ENEMY1剩下2马力或者ENEMY2剩下4马力。有没有办法做到这一点?\
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()
答案 0 :(得分:5)
更好的设计原则不依赖于对象的特定名称,如下所示:
class badguy(object):
def __init__(self):
pass
b = badguy()
print b
>>> <__main__.badguy object at 0x7f2089a74e50> # Not a great name huh? :D
这可能导致一大堆问题带有赋值绑定,引用,最重要的是不允许您按用户或程序命名对象选择。
如果要允许在类的范围之外进行访问,请将实例变量添加到名为self._name
(9.6 Classes - Private Variables)或self.name
的类中(在此示例中为,你可以命名任何东西)。这不仅仅是面向对象的设计,而且现在您可以实现像__hash__
这样的方法,以便能够基于名称创建哈希,例如使用对象作为键(为什么这个设计选择更好的原因还有很多原因!)。
class badguy(object):
def __init__(self, name=None):
self.hp = 4
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
def attack(self):
print("hit")
self.hp -= 1
def still_alive(self):
if self.hp <=0:
print("enemy destroyed")
else :
print ("{} has {} hp left.".format(self.name, self.hp))
示例输出:
b = badguy('Enemy 1')
print b.name
>>> Enemy 1
b.still_alive()
>>> Enemy 1 has 4 hp left.
b.name = 'Enemy One' # Changing our object's name.
b.still_alive()
>>> Enemy One has 4 hp left.
答案 1 :(得分:1)
你必须先给他们起名字。 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()
答案 2 :(得分:1)
我在这里发布了一个完整的解决方案:
https://stackoverflow.com/a/49331683/7386061
它没有参数。例如,您可以这样做:
class badguy(RememberInstanceCreationInfo):
def __init__(self):
super().__init__()
self.hp = 4
def attack(self):
print("hit")
self.hp -= 1
def still_alive(self):
if self.hp <=0:
print("enemy destroyed")
else :
print (self.creation_name + " has " + str(self.hp) + " hp left")
enemy1 = badguy()
enemy2 = badguy()
enemy1.attack()
enemy1.attack()
enemy1.still_alive()
enemy2.still_alive()
out: hit
out: hit
out: enemy1 has 2 hp left
out: enemy2 has 4 hp left