面向对象有三大特征:多态(对应方法覆写)、封装、继承(对应方法重载),这个在Java中已经说得很详细了,这里面只是介绍Python在这三个特性方面的实现。

  Python和Java一样使用class关键字来创建对象。语法格式如下:

class 类名:
  def 方法名1(参数列表):
    pass

  从上述语法来看,类必须使用class关键字来定义,接着是类名,然后使用pass占位。

一个例子如下:

class Person:
    def getName(self):
        print 'My name is AIQI'
    def getAge(self):
        print 'My age is 27'
    def getHoppy(self):
        print 'My hobby is love you'
>>> import Person
>>> person = Person.Person()
>>> person.getName()
My name is AIQI
>>> person.getAge()
My age is 27
>>> person.getHoppy()
My hobby is love you

实例应用

myStr = raw_input('Please input one object:')
class MyWorld:
    #define one person method
    def printPerson(self):
        self.myTalk = 'I can speak'
        self.myLimbs = 'I can move'
        print 'I am a person so,I can %s, %s' % (self.myTalk, self.myLimbs)
    #define one pig method
    def printPig(self):
        self.myTalk = 'Hengheng...'
        self.myWeight = 'I am fat'
        print 'I am a pig so,%s, %s' % (self.myTalk, self.myWeight)
if __name__ == '__main__':
    myWorld = MyWorld()
    if myStr == 'Person':
        myWorld.printPerson()
    elif myStr == 'Pig':
        myWorld.printPig()
    else:
        print 'No this object'
View Code

相关文章: