TDN*_*DNS 0 python oop methods class
我正在写一个迷你游戏来学习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
Run Code Online (Sandbox Code Playgroud)
以下是使用武器类创建的对象.
# 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
Run Code Online (Sandbox Code Playgroud)
我试图弄清楚为什么swordStrength和magicStaffStrength等于传递给方法的强度值.
任何帮助深表感谢.
谢谢.
你在weapon命名空间中覆盖weaponStrength :
self.weaponStrength = strength
Run Code Online (Sandbox Code Playgroud)
和
def weaponStrength(...):
Run Code Online (Sandbox Code Playgroud)
实际上是冲突的.也许考虑一下你的命名约定