什么时候最好在Python中使用类? [英] When is it best to use a class in Python?

查看:501
本文介绍了什么时候最好在Python中使用类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ p
$ b

例如,在下面的代码中:

 #使用类
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怪物的水平是,self.level
print怪物的伤害是,self.damage
print攻击持续时间是,self.duration

def sleep(self):
print怪物累了,决定休息。

x = Monster(1,2,3)
y = Monster(2,3,4)
x.fight()
y.fight $ b y.sleep()

#使用函数
def fight_func(level,damage,duration):
print怪物的水平是 b打印怪物的伤害是,伤害
print攻击持续时间,持续时间

fight_func(1,2,3)
fight_func )

纯函数版本似乎更干净,给出相同的结果。



是您可以创建的类的主要值,并调用对象上的多个方法,例如战斗或睡觉?

解决方案

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



只使用函数,更难找到一个好的地方来存储状态。


I'm new to python and programming in general, so would really appreciate any clarification on this point.

For example, in the following code:

    #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)

The pure function version seems cleaner and gives the same result.

Is the primary value of classes that you can create and call a number of methods on an object, e.g. fight or sleep?

解决方案

Your example is rather simplified.

In a more complete example fighting wouldn't just display the current state - it would also modify that state. Your monster might get hurt and that would change its hit points and morale. This state has to be stored somewhere. If you use a class it would be natural to add instance variables to store this state.

Using only functions it would be more difficult to find a good place to store the state.

这篇关于什么时候最好在Python中使用类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆