Python使用类(class)和对象(object),进行面向对象(object-oriented programming,简称OOP)的编程。

面向对象的最主要目的是提高程序的重复使用性。我们这么早切入面向对象编程的原因是,Python的整个概念是基于对象的。了解OOP是进一步学习Python的关键。

下面是对面向对象的一种理解,基于分类。


In [6]:
class Bird(object):
    haveFeather = True
    wayOfReproduction = 'egg'
summer = Bird()
print(summer.haveFeather)
print(summer.wayOfReproduction)


True
egg

In [3]:
class Bird(object):
    haveFeather = True
    wayOfReproduction = 'egg'
    def move(self,dx,dy):
        position = [0,0]
        position[0] = position[0]+dx
        position[1] = position[1]+dy
        return position
summer = Bird()
print('after move:',summer.move(5,8))


after move: [5, 8]

In [5]:
#继承
class Chicken(Bird):
    wayOfMove = 'walk';
    possibleInKFC = True;

class Oriole(Bird):
    wayOfMove = 'fly';
    possibleInKFC = False;
chicken = Chicken();
print(chicken.wayOfMove)
print(chicken.move(20,20))


walk
[20, 20]

总结

将东西根据属性归类 ( 将object归为class )

方法是一种属性,表示动作

用继承来说明父类-子类关系。子类自动具有父类的所有属性。

self代表了根据类定义而创建的对象。

建立对一个对象: 对象名 = 类名()

引用对象的属性: object.attribute


In [7]:
'''__init__()方法

__init__()是一个特殊方法(special method)。Python有一些特殊方法。Python会特殊的对待它们。特殊方法的特点是名字前后有两个下划线。

如果你在类中定义了__init__()这个方法,创建对象时,Python会自动调用这个方法。这个过程也叫初始化。
summer = happyBird('Happy,Happy!')
这里继承了Bird类,它的定义见上一讲。
__init__()方法相当于java中的构造方法
'''
class happyBird(Bird):
    def __init__(self,more_words):
        print('We are happy birds.',more_words)

chicken = happyBird("happy happy")


We are happy birds. happy happy

In [12]:
class Human(object):
    def __init__(self,inputGender):
        self.gender = inputGender;
    def genderCheck(self):
        print(self.gender);
        return self.gender;
liLei = Human('male');
liLei.genderCheck();


male

In [ ]:
class Book(object):
    __init__(self,)

In [ ]: