这是我正在处理的某些代码的一部分,我想让两个人知道如何将来自两个不同函数的两个变量也加在一起?
def Dwarf():
Name = "Dwarf "
Health = 150
Mana = 10
Stamina = 15
Base_Attack = 20
Melee_Attack = 0
Elemental_Attack = 5
print("You have choosen Dwarf! \n ")
return
def Mage():
Name = "Mage "
Health = 10
Mana = 20
Stamina = 5
Base_Attack = 5
Melee_Attack = 0
Elemental_Attack = 20
print("Your Class is Mage! \n ")
return
我如何将名称和健康/法术加在一起,以成为种族级人物?并在需要时可以调用它?
用函数执行此操作似乎不合逻辑。似乎您需要使用类。一个类可以具有以下属性(在您的情况下):
和方法,例如:
一个class Dwarf
,看起来像这样:
class Dwarf(object):
def __init__(self):
self.name = "Dwarf"
self.health = 150
# more attributes
def getName(self):
return self.name
# more methods
与Mage
班上有些相似。然后,您可以获取name
as:
dwarf1 = Dwarf()打印dwarf1.getName()
当然,我建议您阅读有关Python中的类的信息。
您还可以将属性值作为参数传递,因此在创建时进行设置:
一个class Dwarf
,看起来像这样:
class Dwarf(object):
def __init__(self, name, health):
self.name = name
self.health = health
# more attributes
def getName(self):
return self.name
# more methods
并创建一个实例:
dwarf2 = Dwarf("strangeNameHere", 200)
笔记:
我建议您遵循Python命名约定。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句