use*_*742 8 python oop class function
我是python和编程的新手,所以非常感谢你对这一点的任何澄清.
例如,在以下代码中:
#Using a class
class Monster(object):
def __init__(self, level, damage, duration):
print self
self.level = level
self.damage = damage
self.duration = duration
def fight(self):
print self
print "The monster's level is ", self.level
print "The monster's damage is ", self.damage
print "The attack duration is ", self.duration
def sleep(self):
print "The monster is tired and decides to rest."
x = Monster(1, 2, 3)
y = Monster(2, 3, 4)
x.fight()
y.fight()
y.sleep()
#just using a function
def fight_func(level, damage, duration):
print "The monster's level is ", level
print "The monster's damage is ", damage
print "The attack duration is ", duration
fight_func(1, 2, 3)
fight_func(5,3,4)
Run Code Online (Sandbox Code Playgroud)
纯函数版本似乎更清晰,并给出相同的结果.
是否可以创建类的主要值并在对象上调用多个方法,例如战斗还是睡眠?
Mar*_*ers 11
你的例子相当简单.
在一个更完整的例子中,战斗不仅会显示当前状态 - 它还会修改该状态.你的怪物可能会受到伤害,这会改变它的生命值和士气.这个状态必须存储在某个地方.如果你使用一个类,添加实例变量来存储这个状态是很自然的.
仅使用函数将更难找到存储状态的好地方.