如何在另一个类中访问一个类的属性?

时间:2017-03-11 00:46:47

标签: python attributes

那么我想做什么呢 那么我正在做的是试图在你的角色和敌人之间建立一个战斗系统 所以它出错了 那么有两个类:

class Ally  

class Enemy

每个班级都有自己独特的名称,健康,攻击和防御属性

class Ally  
    def __init__(self, name, health, attack, defense):  
        self.name = 'goodguy'  
        self.health = 100  
        self.attack = 50  
        self.defense = 30  
class Enemy  
    def __init__(self, name, health, attack, defense):  
        self.name = 'badguy'  
        self.health = 120  
        self.attack = 40   
        self.defense = 20  

但是,Ally和Enemy等级都需要彼此的健康和防御属性才能造成伤害

class Ally(object):  
    def __init__(self, name, health, attack, defense):  
        self.name = goodguy  
        self.health = 100  
        self.attack = 50  
        self.defense = 30  
    def fight(self)  
        (damage moves)  
        Enemy health = Enemy.health - ((self.attack/Enemy.defense)+2)  
    def battle_script(self)   
        while self.health > 0 and Enemy.health > 0:  
            self.fight()  
            if Enemy.health <=0:  
                break  
            Enemy.fight()  
            if self.health <=0:  
                break  
        if Enemy.health() <= 0:  
            print ('The ' + Enemy.name + ' was defeated')  
        if self.health <= 0:  
            print ("You were defeated")  
class Enemy(object):   
    def __init__(self, name, health, attack, defense):  
        self.name = badguy  
        self.health = 120  
        self.attack = 40  
        self.defense = 20  
    def fight(self)  
        (random damage moves)  
        Enemy health = Ally.health - ((self.attack/Ally.defense)+2)  
Ally.battle_scrip()  

所以问题是我不知道如何引入它们各自的属性,即在Enemy.health的战斗脚本中调用,我可能把它全部拉到一个类中,但我宁愿保留它们当我制造更多敌人时分开。

2 个答案:

答案 0 :(得分:1)

首先你创建你的班级bob = Ally();evil_frank = Enemy();的实例...除此之外我根据你给出的代码我不知道你期望发生什么,但我猜你想要的东西如下所示

def fight(ally,enemy):
    while ally.is_alive() and enemy.is_alive():
        ally.hp -= enemy.dmg
        enemy.hp -= ally.dmg
    print "OK FIGHT OVER SOMEONE DIED..."

fight(bob,evil_frank)

答案 1 :(得分:0)

所以你想为Ally:Enemy课程建立一个:很多关系?我要做的是创建一个敌人类对象列表,它们是你的Ally类的成员。你甚至可以向你的Ally构造函数传递一个参数来选择你想要的敌人数量。

应该是这样的:

import itertools    

class Ally(object):  
    def __init__(self, enemies):  
        self.name = goodguy  
        self.health = 100  
        self.attack = 50  
        self.defense = 30
        self.enemies = []
        for _ in itertools.repeat(None, enemies):
            self.enemies.append(Enemy())
...

如果你想要一个很多:很多关系,我会创建另一个可以成为战斗对象的类。让我们称之为&#34; Battle&#34;类。然后你可以为你的盟友和敌人做一个类对象列表的同一个技巧,然后你有在战斗类中进行战斗的逻辑。

class Battle(object):  
    def __init__(self, allies, enemies):  
        self.allies = []
        self.enemies = []
        for _ in itertools.repeat(None, allies):
            self.allies.append(Ally())
        for _ in itertools.repeat(None, enemies):
            self.enemies.append(Enemy())
...