在函数中创建类对象(python)

时间:2017-01-29 12:01:54

标签: python pygame

目前我正在探索Pygame的可能性,并创造了一个简单的游戏,现在我正在努力将其搞砸。我试图通过使用我在函数中创建的类来定义新对象。

这就是我的尝试:

def CreateEnemy():
    enemy1 = Enemies()
    enemy2 = Enemies()
    enemy3 = Enemies()
    enemy1.getInstructions()
    enemy2.getInstructions()
    enemy3.getInstructions()

然而,当我尝试使用对象enemy1时,它说没有定义。据我所知,对象可能只是函数中的本地对象。这是否意味着我必须以某种方式使用return函数?

3 个答案:

答案 0 :(得分:1)

我假设你有一个名为Enemies的课程,如下面的

    <html>
<body bgcolor="cyan">
<h1>The Solar System</h1>
<script>
var planets= ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"];
var endofplanets=planets.length;
var i =0;

function nextplanet(){
if (i<endofplanets){
document.getElementById('p1').innerHTML=planets[i];
i++;
}
else
{
i = 0;
document.getElementById('p1').innerHTML=planets[i];
i++;
}

}
</script>
<script>
function previousplanet(){
if (i>0){
i--;
document.getElementById('p1').innerHTML=planets[i];

}

}
</script>
<p id="p1">---</p>
<button type="button" onclick="nextplanet()">Next Planet</button>
<button type="button" onclick="previousplanet()">Previous Planet</button>
</body>
</html>

现在需要一种方法来创建一堆敌人实例

class Enemies:
  def getInstructions():
    return "instructions"

然后使用上面的方法创建这样的敌人:

def create_enemies(num_of_enemies):
  enemies = []
  for i in range(num_of_enemies):
    enemies.append(enemy)
  return enemies

答案 1 :(得分:0)

请包含一些代码,以便您可以获得更好的答案,但不要求您不需要编写返回函数,如我在示例中所示。

class Enemies:
    def getInstructions(self):
        print("Instructions")

def createEnemy():
    global allEnemy
    allEnemy.append(Enemies())

allEnemy = []
createEnemy()
createEnemy()

for enemy in allEnemy :
    enemy.getInstructions()

答案 2 :(得分:0)

class Ins_Normal():
  def getInstructions(self, *args):
    return "GetInstructions_Normal"

class Ins_Agressive():
  def getInstructions(self, *args):
    return "GetInstructions_Agressive"


class Enemies(object):
  def __init__(self, behaivor = 'Ins_Normal', mode = True, *args):
    self.behaivor = behaivor
    self.mode = mode

  def getInstructions(self, *args):
    #create instance based on behaivor
    try:
        ins = globals()[self.behaivor]() # same like ins = Ins_Agressive()
    except KeyError as e:
        raise NotImplementedError(e)
    # return getInstructions() init value behaivor
    return ins.getInstructions()

  def xyz(self, *args):
    # if True return worldspace position (eg)
    if self.mode:
      return "xyz"
    return 'com_xyz'

def CreateEnemy(enemy = 0, behaivor = 'Ins_Normal', mode =True):
    # wrapper function to collect Enemies 
    # create dict, so no hardcoded variabels, scalable....
    data = dict((_id, Enemies(behaivor, mode)) for _id in range(enemy))
    return data

# create groups of enemies
enemies_com_normal = CreateEnemy(3, 'Ins_Normal') #com
enemies_user_normal = CreateEnemy(3, 'Ins_Normal', True) #interactive
enemies_com_agressive = CreateEnemy(5, 'Ins_Agressive', True) #interactive

print enemies_com_normal
# we get dict of Enemy instances with id(int) as key
#>>> {0: <Enemies object at 0x7f2d8cfe5b10>, 1: <Enemies object at 0x7f2d8cfe5b50>, 2: <Enemies object at 0x7f2d8cfe5b90>}

#lets print some infos of the agents
print enemies_com_normal[0].xyz()
#>>>xyz
print enemies_com_normal[0].getInstructions()
#>>>GetInstructions_Normal
print enemies_com_agressive[2].getInstructions()
#>>>GetInstructions_Agressive

enemies_com_hgd = CreateEnemy(5, 'Ins_HGD', True) #interactive
print enemies_com_hgd[0].getInstructions()

#Traceback (most recent call last):
#  File "python", line 56, in <module>
#  File "python", line 21, in getInstructions
#NotImplementedError: 'Ins_HGD' <<<<< no Instruction Implemented for  Ins_HGD