Ces*_*ian 0 python variables class dynamic-data python-2.7
对于上下文,我正在使用RPG中的库存系统,我正在使用python代码进行原型设计.
我不明白的是如何为项目的每个实例创建单独的变量而不手动声明它们.举个简短的例子:
class Player(object):
def __init__(self):
self.Items = {}
class Item(object):
def __init__(self):
self.Equipped = 0
class Leather_Pants(Item):
def __init__(self):
#What do i place here?
def Pick_Up(self, owner):
owner.Items[self.???] = self #What do i then put at "???"
def Equip(self):
self.Equipped = 1
PC = Player()
#Below this line is what i want to be able to do
Leather_Pants(NPC) #<-Create a unique instance in an NPC's inventory
Leather_Pants(Treasure_Chest5) #Spawn a unique instance of pants in a treasure chest
Leather_Pants1.Pick_Up(PC) #Place a specific instance of pants into player's inventory
PC.Items[Leather_Pants1].Equip() #Make the PC equip his new leather pants.
Run Code Online (Sandbox Code Playgroud)
如果我在上面的代码中做了些蠢事,请指出.
如果代码没有说清楚我想要做的是我希望能够在我生成它们时为所有项动态创建变量,因此没有两个项将共享相同的变量名,它将作为标识符用于我.
我不介意我是否必须使用另一个类或函数,如"Create_Item(Leather_Pants(),Treasure_Chest3)"
什么是最好的方法,或者如果你认为我做错了,哪种方式会更正确?
作为一般规则,您不希望创建动态变量,并且希望将数据保留在变量名称之外.
而不是试图创建命名变量pants0,pants1等等,为什么不直接创造,说,所有的皮裤一个列表?然后你就做了pants[0],pants[1]等等.你的代码的其他任何部分都不必知道裤子的存储方式.所以你的所有问题都消失了.
同时,您可能不希望创建Leather_Pants自动将其自身添加到全局环境中.只需正常分配即可.
所以:
pants = []
pants.append(Leather_Pants(NPC))
pants.append(Leather_Pants(chests[5]))
pants[1].pickup(PC)
Run Code Online (Sandbox Code Playgroud)
裤子不必知道他们是#1.每当你调用一个方法时,他们就会得到一个self可以使用的参数.玩家的物品不需要为每个物品映射一些任意名称; 只需将项目直接存储在列表或集合中.像这样:
class Player(object):
def __init__(self):
self.Items = set()
class Item(object):
def __init__(self):
self.Equipped = 0
class Leather_Pants(Item):
def __init__(self):
pass # there is nothing to do here
def Pick_Up(self, owner):
self.owner.Items.add(self)
def Equip(self):
self.Equipped = 1
Run Code Online (Sandbox Code Playgroud)