我是 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)
纯函数版本看起来更干净,并给出相同的结果。
您可以在对象上创建和调用多个方法(例如战斗或睡眠)的类的主要价值是什么?