在Python中为类分配特定的东西

时间:2015-02-26 00:59:58

标签: class python-2.7

好的,这是一个非常基本的问题,但我正在努力提高代码的效率。我有一个基于文本的游戏,我现在每个武器都有一个单独的类,每个武器都有独立操作的变量。我正在使用Python 2.7 IDE。这就是我的代码:(另外,我如何引用每种武器的属性?)

class Weapon1():
owned = True
damage = 2
accuracy = 75

class Weapon2():
owned = False
damage = 4
price = 50
accuracy = 95

class Weapon3():
owned = False
damage = 8
price = 250
accuracy = 50

class Weapon4():
owned = False
damage = 10
price = 500
accuracy = 60

class Weapon5():
owned = False
damage = 10
price = 500
accuracy = 60

2 个答案:

答案 0 :(得分:0)

class Weapon(object):
    def __init__(self, owned, damage, price, accuracy):
        self.owned = owned
        self.damage = damage
        self.price = price
        self.accuracy = accuracy
    def __repr__(self):
        guts = ', '.join('{0}={1!r}'.format(k,v) for k,v in self.__dict__.items())
        return '{0}({1})'.format(self.__class__.__name__, guts)


weapons = [
    Weapon(owned=True,  damage=2,  price=None, accuracy=75),
    Weapon(owned=False, damage=4,  price=50,   accuracy=95),
    Weapon(owned=False, damage=8,  price=250,  accuracy=50),
    Weapon(owned=False, damage=10, price=500,  accuracy=60),
    Weapon(owned=False, damage=10, price=500,  accuracy=60),
]

for i, w in enumerate(weapons, start=1):
    print i, w


# to access individual properties
wielded = weapons[0]
print "damage of wielded weapon:", wielded.damage

给出:

1 Weapon(price=None, damage=2, owned=True, accuracy=75)
2 Weapon(price=50, damage=4, owned=False, accuracy=95)
3 Weapon(price=250, damage=8, owned=False, accuracy=50)
4 Weapon(price=500, damage=10, owned=False, accuracy=60)
5 Weapon(price=500, damage=10, owned=False, accuracy=60)

damage of wielded weapon: 2

答案 1 :(得分:0)

您可以拥有一个Weapon类,然后让不同类型的武器成为该类的实例。以下实现假定您为每个武器赋予price属性。

class Weapon(object):

    def __init__(self, owned, damage, price, accuracy):
        self.owned = owned
        self.damage = damage
        self.price = price
        self.accuracy = accuracy


weapon1 = Weapon(
    owned = True,
    damage = 2,
    price = None,
    accuracy = 75
)

weapon2 = Weapon(
    owned = False,
    damage = 4,
    price = 50,
    accuracy = 50
)

...

依此类推,为你所有的武器。然后,您可以访问各个实例的属性,如下所示。

>>> weapon2.accuracy
95
>>> weapon1.owned
True