基于文件在Python中创建对象

时间:2017-12-25 23:39:59

标签: python python-3.x oop

我正在使用Python 3编写游戏代码,我需要根据文件内容为每个对象属性创建一个未知数量的对象。

为了解释,我将在这里转储一些代码:

class attack(object):
    def __init__(self, name, power):
        self.name = name
        self.element = int(power)

import getline from linecache

Attacks = []

count = 1
while 1==1:
  line=getline("Attacks.txt", count)
  line = line.rstrip()
  if line == "":
    break
  else:
    linelist = line.split()
    #something involving "attack(linelist[1], linelist[2])"
    Attacks.append(item)
  count += 1

“Attacks.txt”包含:

0 Punch 2
1 Kick 3
2 Throw 4
3 Dropkick 6
4 Uppercut 8

代码完成后,列表“Attacks”应该包含5个攻击对象,每个“Attacks.txt”行一个,列出名称和权限。该名称仅供用户使用;在代码中,每个对象只会被其列表中的位置调用。

这个想法是最终用户可以更改“Attacks.txt”(以及其他类似文件)来添加,删除或更改条目;这样,他们可以修改我的游戏,而无需在实际代码中进行挖掘。

问题是我不知道如何动态创建对象,或者我是否可以。我已经有了从文件构建列表的工作代码;唯一的问题是对象的创建。

我的问题,简单地说,我该怎么做?

2 个答案:

答案 0 :(得分:0)

有一天我遇到了同样的问题:

How to call class constructor having its name in text variable? [Python]

您显然必须定义名称在文件中的类。我认为已经完成了。您需要将它们放在当前模块命名空间module.js:538 throw err; ^ Error: Cannot find module '@ngtools/json-schema' at Function.Module._resolveFilename (module.js:536:15) at Function.Module._load (module.js:466:25) at Module.require (module.js:579:17) at require (internal/module.js:11:18) at Object.<anonymous> (/usr/local/lib/node_modules/@angular/cli/models/config/config.js:6:23) at Module._compile (module.js:635:30) at Object.Module._extensions..js (module.js:646:10) at Module.load (module.js:554:32) at tryModuleLoad (module.js:497:12) at Function.Module._load (module.js:489:3)

globals()

答案 1 :(得分:0)

您可以创建一个类,以便提供重载运算符来支持操作:

class Operation:
   def __init__(self, *header):
      self.__dict__ = dict(zip(['attack', 'power'], header))
class Attack:
   def __init__(self, *headers):
     self.__dict__ = {"attack{}".format(i):Operation(*a) for i, a in enumerate(headers, start=1)}
   def __setitem__(self, attack_type, new_power):
      self.__dict__ = {a:Operation(attack_type, new_power) if b.attack == attack_type else b for a, b in self.__dict__.items()}
   def __getitem__(self, attack):
      return [b.power for _, b in self.__dict__.items() if b.attack == attack]
   @property
   def power_listings(self):
      return '\n'.join(['{} {}'.format(*[b.attack, b.power]) for _, b in self.__dict__.items()])

with open('filename.txt') as f:
    f = [i.strip('\n').split() for i in f]
a = Attack(*f)
print(a.power_listings)
a['Throw'] = 6 #updating the power of any occurrence of Throw

输出:

Throw 6
Kick 3
Punch 2
Uppercut 8
Dropkick 6