python定义class

python也是面向对象的语言,类的重要性不言而喻。

class Animal:
    def __init__(self,voice='hello'):
        self.voice=voice
    def __del__(self):
        pass
    def Say(self):
        print self.voice

类名:Animal,构造函数__init__()有一个参数voice,默认值是'hello';我发现python里面的方法都有一个参数self,这样就可以很方便的用自己类中的属性、方法等。

__del__()是析构函数。

如何运行,打开python->import sys->sys.path.append("/py/"),根据自己路径->import animal,文件名->a=animal.Animal()创建该类的对象->a.Say(),调用该类的方法。

类的继承:

class Animal:
    def __init__(self,voice='hello'):
        self.voice=voice
    def __del__(self):
        pass
    def Say(self):
        print self.voice
    def Run(self):
        pass
class Cat(Animal):
    def MyVoice(self,voice):
        self.voice=voice
    def Run(self):
        print 'I am a cat.'

Cat类继承自Animal类,并新加了MyVoice()方法,重载了父类的Run()方法。

 

posted @ 2013-08-22 10:45  楠楠IT  阅读(297)  评论(0编辑  收藏  举报