第九章、 类与面向对象
1)    类
基本类/超类/父类被导出类或子类继承。
Inheritance继承
Inheritance is based on attribute lookup in Python (in X.name expressions).
Polymorphism多态
In X.method, the meaning of method depends on the type (class) of X.
Encapsulation封装
Methods and operators implement behavior; data hiding is a convention by default.

class C1():
    def __init__(self, who):
        self.name = who
I1 = C1('bob')
print I1.name #bob 

2)    命名空间

X = 11              # Global (module) name/attribute (X, or manynames.X)
def f():
    print(X)        # Access global X (11)
def g():
    X = 22          # Local (function) variable (X, hides module X)
    print(X)
class C:
    X = 33          # Class attribute (C.X)
    def m(self):
        X = 44      # Local variable in method (X)
        self.X = 55 # Instance attribute (instance.X)

print(X)          # 11: module (manynames.X outside file)
f()               # 11: global
g()                   # 22: local
print(X)         # 11: module name unchanged
obj = C()         # Make instance
print(obj.X)      # 33: class name inherited by instance
obj.m()           # Attach attribute name X to instance now
print(obj.X)      # 55: instance
print(C.X)        # 33: class (a.k.a. obj.X if no X in instance)
#print(C.m.X)     # FAILS: only visible in method
#print(g.X)       # FAILS: only visible in function

3)    Self参数
指向对象本身

4)    __init__构造器
如果没有__init__,则需要自己定义并赋值

class C1():                # Make and link class C1
    def setname(self, who):      # Assign name: C1.setname
        self.name = who          # Self is either I1 or I2
I1 = C1()                        # Make two instances,

#没有__init__,实例就是个空的命名空间

I1.setname('bob')                # Sets I1.name to 'bob'
print(I1.name)                   # Prints 'bob'

构造器,创建时例时自动调用。

5)    继承搜索的方法
An inheritance search looks for an attribute first in the instance object, then in the class the instance was created from, then in all higher superclasses, progressing from the bottom to the top of the object tree, and from left to right (by default).

6)    一个例子

class AttrDisplay:
    def gatherAttrs(self):
        attrs = []
        for key in sorted(self.__dict__):
            attrs.append('%s=%s' % (key, getattr(self, key)))
        return ', '.join(attrs)
    def __str__(self):
        return '[%s: %s]' % (self.__class__.__name__, self.gatherAttrs())

class Person(AttrDisplay): #Making Instances
    def __init__(self, name, job=None, pay=0): # Add defaults
        self.name = name # Constructor takes 3 arguments
        self.job  = job  # Fill out fields when created
        self.pay  = pay  # self is the new instance object
    def lastName(self):     # Assumes last is last
        return self.name.split()[-1]
    def giveRaise(self, percent):   # Percent must be 0..1
        self.pay = int(self.pay * (1 + percent))

class Manager(Person):
    def __init__(self, name, pay):
        Person.__init__(self, name, 'mgr', pay)
    def giveRaise(self, percent, bonus=.10):
        Person.giveRaise(self, percent + bonus)

if __name__ == '__main__': # Allow this file to be imported as well as run/tested
    bob = Person('Bob Smith')
    sue = Person('Sue Jones', job='dev', pay=100000)
    print(bob)
    print(sue)
    print(bob.lastName(), sue.lastName())
    sue.giveRaise(.10)
    print(sue)
    tom = Manager('Tom Jones', 50000)
    tom.giveRaise(.10)
    print(tom.lastName())
    print(tom) 

python 教程 第九章、 类与面向对象的更多相关文章

  1. Objective-C 基础教程第九章,内存管理

    目录 Object-C 基础教程第九章,内存管理 前言: 对象生命周期 引用计数 RetainCount1项目例子 对象所有权 访问方法中的保留和释放 自动释放 所有对象放入池中 自动释放池的销毁时间 ...

  2. Python 数据分析—第九章 数据聚合与分组运算

    打算从后往前来做笔记 第九章 数据聚合与分组运算 分组 #生成数据,五行四列 df = pd.DataFrame({'key1':['a','a','b','b','a'], 'key2':['one ...

  3. Python:从入门到实践--第九章-类--练习

    #.餐馆:创建一个名为Restaurant的类,其方法_init_()设置两个属性:restaurant_name和cuisine_type. #创建一个名为describe_restaurant的方 ...

  4. 《JS权威指南学习总结--第九章 类和模板》

    内容要点: 一. 1.第六章详细介绍了JS对象,每个JS对象都是一个属性集合,相互之间没有任何联系.在JS中也可以定义对象的类,让每个对象都共享某些属性,这种"共享"的特性是非常有 ...

  5. python 教程 第一章、 简介

    第一章. 简介 官方介绍: Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程.Python简洁的语法和对动态输入的支持,再加上解释性语言的本质,使 ...

  6. Flask 教程 第九章:分页

    本文翻译自The Flask Mega-Tutorial Part IX: Pagination 这是Flask Mega-Tutorial系列的第九部分,我将告诉你如何对数据列表进行分页. 在第八章 ...

  7. Python 【第九章】 Django基础

    在windows 命令行上安装Django 在CMD命令行中输入以下命令进行安装. pip install Django 在windows python安装目录上会出现 一个django-admin. ...

  8. C#图解教程 第九章 语句

    语句 什么是语句控制流语句if语句if-else语句while循环do循环for循环 for语句中变量的作用域初始化和迭代表达式中的多表达式 switch语句 分支示例switch语句补充分支标签 跳 ...

  9. 进击的Python【第九章】:paramiko模块、线程与进程、各种线程锁、queue队列、生产者消费者模型

    一.paramiko模块 他是什么东西? paramiko模块是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. 先来个实例: import param ...

随机推荐

  1. angular自定义管道

    原文地址 https://www.jianshu.com/p/5140a91959ca 对自定义管道的认识 管道的定义中体现了几个关键点: 1.管道是一个带有“管道元数据(pipe metadata) ...

  2. Java虚拟机解析篇之---内存模型

    今天闲来无事来,看一下Java中的内存模型和垃圾回收机制的原理.关于这个方面的知识,网上已经有非常多现成的资料能够供我们參考,可是知识还是比較杂的,在这部分知识点中有一本书不得不推荐:<深入理解 ...

  3. ios开发网络学习四:NSURLConnection大文件断点下载

    #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...

  4. RocketMQ 安装详细说明

    原文:RocketMQ 安装详细说明 目录 本文导读 环境说明 RocketMQ 下载 从 Apache 下载 从 GitHub 下载 RocketMQ 安装 文件上传 项目解压 编译部署 Rocke ...

  5. Android UI:看看Google官方自定义带旋转动画的ImageView-----RotateImageView怎么写(附 图片淡入淡...)

    众所周知,想要让ImageView旋转的话,可以用setRotation()让其围绕中心点旋转,但这个旋转是不带动画的,也就是旋转屏幕时图片噌的一下就转过去了,看不到旋转的过程,此UI体验不大好,为此 ...

  6. swf loading 自身

    stop(); import flash.net.URLRequest; import caurina.transitions.Tweener; loaderInfo.addEventListener ...

  7. [React] Render Basic SVG Components in React

    React loves svg just as much as it loves html. In this lesson we cover how simple it is to make SVG ...

  8. phpStorm怎么解决502 bad gateway(总结整理)

    phpStorm怎么解决502 bad gateway(总结整理) 一.总结 1.配置 php解释器. 二.phpStorm解释器与服务器配置(解决502 bad gateway与404 not fo ...

  9. 小强的HTML5移动开发之路(41)——jqMobi中Side Menu实现(类似人人网)

    记得以前在做Native App的时候类似于人人网侧边滑动的效果非常的热,很多app仿照该效果进行开发,在jqMobi中也有类似的效果被称为Side Menu.下面我们来一步一步实现该效果. 首先新建 ...

  10. XMPP之ios即时通讯客户端开发-配置XMPP基本信息(四)

    前文已经有配置open fire,接下来要通过XMPP框架链接到open fire的服务器: 1.首先要在系统偏好设置里面打开open fire的服务器 2.代码中设置xmpp的myJID 有几个名词 ...