我正在尝试使用python进行OOP,
该项目正在创建一些随机生成的RPG角色
我遇到的问题是我正在创建这些随机生成的字符的列表,并希望在那里打印统计信息。
以下是随机生成字符的方式:
def generateCharacters():
classes = ["B", "E", "W", "D", "K"]
choice = random.choice(classes)
if choice == "B":
return barbarian(70, 20, 50)
elif choice == "E":
return elf(30, 60, 10)
elif choice == "W":
return wizard(50, 70, 30)
elif choice == "D":
return dragon(90, 40, 50)
elif choice == "K":
return knight(60, 10, 60)
这是野蛮阶级,所有其他阶级或多或少都是相同的:
class barbarian(character):
def __init__(self, charPower, charSAttackPwr, charSpeed):
# Getting the properties from the inheritted character Base Class
character.__init__(self, "B", 100)
self.power = charPower
self.sAttackPwr = charSAttackPwr
self.speed = charSpeed
# Method for getting and returning all the stats of the character
def getStats(self):
# Creating a string to hold all the stats, using concatenation
stats = "Name: %s, Type: %s, Health: %s, Power: %s, Special Attack
Power: %s, Speed: %s" % (self.name, self.type, self.health,
self.power, self.sAttackPwr, self.speed)
# Returns stats to the the function that called
return stats
我创建了一个名为getStats的方法,该方法使用字符串连接来创建一个显示所有统计信息的字符串:
# Method for getting and returning all the stats of the character
def getStats(self):
# Creating a string to hold all the stats, using concatenation
stats = "Name: %s, Type: %s, Health: %s, Power: %s, Special Attack Power: %s, Speed: %s" % (self.name, self.type, self.health, self.power, self.sAttackPwr, self.speed)
# Returns stats to the the function that called
return stats
当我运行代码时,它将调用main(),依次调用menu():
def menu(gameChars):
print("Welcome to the RPG Character Simulator")
print("Here is your randomly generated team: ")
for x in gameChars:
print(x.getStats)
def main():
gameChars = []
for x in range(10):
y = generateCharacters()
gameChars.insert(x, y)
#z = generateCharacters()
menu(gameChars)
#print(z.getStats)
使用示例,我期望从print(x.getStats)获得的输出为:
Name: bob, Type: barbarian, Health: 100, Power: 70, Special Attack Power: 20, Speed: 20
但是,我得到了:
<bound method barbarian.getStats of <__main__.barbarian object at 0x000001F56A195668>>
这个我想念什么?以及如何获得预期的输出?
在此先感谢您的帮助
答案 0 :(得分:0)
替换此:
print(x.getStats)
与此:
print(x.getStats())
答案 1 :(得分:0)
另一个版本是使用@property
装饰器:
class Barbarian(Character):
@property
def getStats(self):
return 'Name: {.name}'.format(self)
这将允许:
bob = Barbarian('bob', …)
print(bob.getStats)
按预期工作