0

我正在编写一个小游戏来学习 Python。我创建了一个可以导入到我的 main.py 文件中的武器类。

这是我制作的课程:

class weapon(object):

    def __init__(self, name):
        self.weaponName = name

    def weaponStrength(self, level, strength):
        self.weaponLevel = level
        self.weaponStrength = strength
        damage = self.weaponStrength * level

        print "Damage is equal to %r" % damage

        return damage

以下是使用武器类创建的对象。

# Creates an Object called sword using the weaponsClass
sword = weapon("sword")

# Calls a method of the weaponsClass to calculate weapon Strength. Returns a int
sword.weaponStrength(3, 20)

# Creates an Object called Magic Staff using the weaponsClass
magicStaff = weapon("Magic Staff")

# Calls a method of the weaponsClass to calculate weapon Strength. Returns a int
magicStaff.weaponStrength(5, 30)


# Sets a variable
swordStrength = sword.weaponStrength

# Sets a variable
magicStaffStrength = magicStaff.weaponStrength

# Prints the variable
print swordStrength

# Prints the variable
print magicStaffStrength

我试图弄清楚为什么 SwordStrength 和 magicStaffStrength 等于传递给该方法的强度值。

任何帮助深表感谢。

谢谢。

4

2 回答 2

6

您正在覆盖weapon命名空间中的武器强度:

self.weaponStrength = strength

def weaponStrength(...):

实际上是矛盾的。也许考虑一下您的命名约定

于 2012-04-10T19:52:30.247 回答
0

此方法试图做两件事:

存储武器等级和武器强度

计算和返回伤害

我认为这是一个糟糕的设计,因为第一个目的表明该函数应该被调用,setWeaponLevelAndStrength而第二个目的表明它应该被调用calculateDamageweaponStrength如果您还希望有一个具有该名称的属性,那么显然是一个糟糕的名称选择

def weaponStrength(self, level, strength):
    self.weaponLevel = level                #first purpose
    self.weaponStrength = strength          #first purpose
    damage = self.weaponStrength * level    #second purpose

    print "Damage is equal to %r" % damage  #second purpose

    return damage

我建议你把方法一分为二

def setWeaponLevelAndStrength(self, level, strength):
    self.weaponLevel = level
    self.weaponStrength = strength

def calculateDamage(self)
    damage = self.weaponStrength * self.weaponLevel

    print "Damage is equal to %r" % damage

    return damage
于 2012-04-10T20:19:41.247 回答