什么时候最好使用Python中的类?

2024-04-30 01:30:24 发布

您现在位置:Python中文网/ 问答频道 /正文

一般来说,我对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)

纯函数版本看起来更干净,并给出相同的结果。在

你可以在一个对象上创建和调用许多方法的类的主要值,例如fight或sleep?在


Tags: theselfisdefsleeplevelclassfunc
3条回答

你的例子相当简单。在

在一个更完整的例子中,战斗不仅显示当前状态,还将修改状态。你的怪物可能会受伤,这会改变它的生命值和士气。这种状态必须存储在某处。如果使用类,则添加实例变量来存储此状态是很自然的。在

如果只使用函数,就很难找到一个存储状态的好地方。在

我的怪物呢?他可以和另一个怪物战斗!想必你的功能性怪物做不到;-)

class Monster(object): 
    def __init__(self, level, damage, duration): 
        self.level    = level
        self.damage   = damage
        self.duration = duration
    def fight(self, enemy):
        if not isinstance(enemy, Monster) :
            print "The enemy is not a monster, so I can't fight it."
            return None
        else :
            print "Starting fighting"
        print "My monster's level is ", self.level
        print "My monster's damage is ", self.damage
        print "My monster's attack duration is ", self.duration
        print "The enemy's level is ", enemy.level
        print "The enemy's damage is ", enemy.damage
        print "The enemy's attack duration is ", enemy.duration

        result_of_fight = 3.*(self.level    - enemy.level)  + \
                          2.*(self.damage   - enemy.damage) + \
                          1.*(self.duration - enemy.duration)
        if result_of_fight > 0 :
            print "My monster wins the brutal battle"
        elif result_of_fight < 0 :
            print "My monster is defeated by the enemy"
        else :
            print "The two monsters both retreat for a draw"
        return result_of_fight
    def sleep(self, days): 
        print "The monster is tired and decides to rest for %3d days" % days
        self.level    += 3.0 * days
        self.damage   += 2.0 * days
        self.duration += 2.0 * days
x = Monster(1, 2, 3)
y = Monster(2, 3, 4)
x.fight(y)
x.sleep(10) 

所以:

^{pr2}$

你的例子不是特别有趣-它只打印了三个数字。你甚至不需要函数。在

但是如果你需要编写一个程序,它必须同时跟踪两个不同的怪物,了解它们的健康状况,区分它们的战斗能力,因此,你可以看到将每个怪物封装在一个单独的怪物实例中的价值。在

相关问题 更多 >