面向对象编程1



1. 什么是面向对象编程(OOP)

http://baike.baidu.com/view/63596.htm

1.1 什么是对象?

Object,物件,东西

属性,可以被描述;动作, 完成某件事

1.2 通俗来讲:一切皆对象

抽象的看世界

同函数一样,函数是对逻辑的抽象,对过程的抽象。而对象是对具体事物(数据)和操作的抽象

比如: s = ‘huyang’ s 就是个对象

再比如函数

def say():pass
say.func_name

1.3 什么是面向?Oriented (导向)

以对象为导向

所以OOP就是,用以对象为导向的方式来编程。以对象为基础,注意,之前是以函数为基础来编程。

java中一级公民: class, print ‘hello’

python中一级公民: function : print(‘hello’)

类是OOP的主要工具

1.4 为什么要面向对象

先来回忆下函数之前

进一步的抽象–我们想描述这个世界

1.5 面向对象三要素:

封装,继承,多态

封装

将数据抽象为对象,包含自己所需的数据,提供接口给外部使用

优点:减少耦合–数据独立,只暴露接口

还是打个比喻:外卖窗口,只有一个进出的接口

继承

通过某种方式拥有另外一个对象(类)所有的属性和方法。

优点:复用

举例:重复的东西抽取出去,形成基类

多态:鸭子类型(duck type)(嘎嘎叫的就是鸭子),不同的对象可以相互替代,只要他们有相同的属性或者方法

2. Python中怎么定义对象

2.1 class关键字

class Human:
    name = 'anyone'
    def __init__(self, name):
        self.name = name

    def eat(self, food_name):
        print self.name, 'eat', food_name

    def speak(self, words):
        print  self.name, ' shuo ', words

human = Human('someone')
print human.name
human.eat('hotdog')
human.speak('very good')

self是什么?一定是self吗?

2.2 类 和 实例

2.2.1 怎么继承

class Boy(Human):
    def buy_food(self, food_name):
            print self.name, 'go to buy', food_name
            return food_name

boy = Boy('xiaozhang')
print boy.name
boy.buy_food('bacai')
boy.eat('baicai')

class Girl(Human):
    def cook_food(self, food):
        print self.name, 'cook', food

2.2.2 演示多态

h = None
who = raw_input('chose person, boy or girl')
if who == 'boy:
    h = Boy('test')
elif who == 'girl':
    h = Girl('lili')
else:
    h = Human('nobody')

h.speak('how are you')

3. 新式类和老式类

3.1 老式类

# class T:
#     pass
In [1]: class Person:
   ...:     name = []
   ...:

In [2]: p1 = Person()

In [31]: p1.__class__
Out[31]: <class __main__.Person at 0x7ff697d87c80>

In [32]: type(p1)
Out[32]: instance

3.2 新式类

# class T(object):
#     pass
In [34]: class Person2(object):
   ....:     name = []
   ....:

In [35]: p3 = Person2()

In [36]: p3.__class__
Out[36]: __main__.Person2

In [37]: type(p3)
Out[37]: __main__.Person2

In [38]: dir(Person)
Out[38]: ['__doc__', '__module__', 'name']

In [39]: dir(Person2)
Out[39]:
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 'name']

In [40]: Person2.__class__
Out[40]: type

The Inside Story on New-Style Classes by Guido

4. 作业

4.1 作业1:使用timeit模块,对比正则表达式,先编译快,还是直接使用search搜索快

4.2 作业2: 总结新式类和旧式类的区别。

4.3 作业3:使用面向对象的方式,完成大白想吃饭,不会做,去找大红做饭的场景,越细致越好。食物可以定义为类。

4.4 讲题总结

4.4 NEW MODULE

collections - High-performance container datatypes

DESCRIPTION:
This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers, dict, list, set, and tuple.
这个模块是一个特殊的数据类型容器,在python内置的数据类型容器(dict, list, set, and tuple)之外提供了一个新的选择

FUNCTIONS:
namedtuple() - Factory Function for Tuples with Named Fields
Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index.
namedtuple()在tuple中赋予每一个位置以具体的含义,使它更具可读性。它可以用在所有常规tuples存在的地方,用具体的名称代替数字index

SYNTAX:
collections.namedtuple(typename, field_names[, verbose=False][, rename=False])
typename, 自建数据类型名称
field_names, 用来替代数字index的字符串
# 导入namedtuple函数
>>> from collections import namedtuple

# 创建yanse类型,使用一个list来做索引
>>> Color = namedtuple('yanse', ['red', 'green', 'blue'])

# 创建一个tuple实例
>>> color  = Color(55, 155, 255)

# 可以用类似类与方法调用的方式
>>> print color.red, color.blue, color.green
55 255 155

# 看看color的类型
>>> type(color)
<class '__main__.yanse'>

官方文档

json

pickle