python 教程 第九章、 类与面向对象
第九章、 类与面向对象
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 教程 第九章、 类与面向对象的更多相关文章
- Objective-C 基础教程第九章,内存管理
目录 Object-C 基础教程第九章,内存管理 前言: 对象生命周期 引用计数 RetainCount1项目例子 对象所有权 访问方法中的保留和释放 自动释放 所有对象放入池中 自动释放池的销毁时间 ...
- Python 数据分析—第九章 数据聚合与分组运算
打算从后往前来做笔记 第九章 数据聚合与分组运算 分组 #生成数据,五行四列 df = pd.DataFrame({'key1':['a','a','b','b','a'], 'key2':['one ...
- Python:从入门到实践--第九章-类--练习
#.餐馆:创建一个名为Restaurant的类,其方法_init_()设置两个属性:restaurant_name和cuisine_type. #创建一个名为describe_restaurant的方 ...
- 《JS权威指南学习总结--第九章 类和模板》
内容要点: 一. 1.第六章详细介绍了JS对象,每个JS对象都是一个属性集合,相互之间没有任何联系.在JS中也可以定义对象的类,让每个对象都共享某些属性,这种"共享"的特性是非常有 ...
- python 教程 第一章、 简介
第一章. 简介 官方介绍: Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程.Python简洁的语法和对动态输入的支持,再加上解释性语言的本质,使 ...
- Flask 教程 第九章:分页
本文翻译自The Flask Mega-Tutorial Part IX: Pagination 这是Flask Mega-Tutorial系列的第九部分,我将告诉你如何对数据列表进行分页. 在第八章 ...
- Python 【第九章】 Django基础
在windows 命令行上安装Django 在CMD命令行中输入以下命令进行安装. pip install Django 在windows python安装目录上会出现 一个django-admin. ...
- C#图解教程 第九章 语句
语句 什么是语句控制流语句if语句if-else语句while循环do循环for循环 for语句中变量的作用域初始化和迭代表达式中的多表达式 switch语句 分支示例switch语句补充分支标签 跳 ...
- 进击的Python【第九章】:paramiko模块、线程与进程、各种线程锁、queue队列、生产者消费者模型
一.paramiko模块 他是什么东西? paramiko模块是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. 先来个实例: import param ...
随机推荐
- 计算机图形学(二)输出图元_3_画线算法_2_DDA算法
DDA算法 数字微分分析仪(digital differential analyzer, DDA)方法是一种线段扫描转换算法.基于使用等式(3.4)或等式(3.5)计算的&x或& ...
- Qt信号槽传递自定义类型参数(qRegisterMetaType)
1 #include <QMetaType>//记得包含这个头文件 2 //my_type是我自己定义的类型 3 qRegisterMetaType<my_type>(&quo ...
- Xcode5新特性之注释
Xcode5新特性之注释 Xcode5在注释式文档方面也有进步,越来越象javadoc. Xcode4 参考一下教程 http://blog.chukong-inc.com/index.php/201 ...
- [Node.js] Create a model to persist data in a Node.js LoopBack API
In this lesson you will learn what a LoopBack model is, you will create a Product model using the Lo ...
- CentOS 7安装fcitx中文输入法
安装过程例如以下: 1.增加EPEL源 EPEL7差点儿是CentOS必备的源: sudo yum install epel-release 2.加入mosquito-myrepo源 mosquito ...
- MySQL慢日志的相关参数
slow-query-log = on #开启MySQL慢查询功能 slow_query_log_file = /data/mysql/testdb-slow.log #设置MySQL慢查询日志路径 ...
- [Ramda] Create a Query String from an Object using Ramda's toPairs function
In this lesson, we'll use Ramda's toPairs function, along with map, join, concatand compose to creat ...
- 使用Spring Tool Suite (STS)新的工作空间无需再配置
在你的新的工作空间中找到比如 F:\java-wokespace\你的新的工作空间名称\.metadata\.plugins\org.eclipse.core.runtime\.settings 找到 ...
- database software runInstaller无法看到全部的rac节点的处理方法
近期遇到一个问题:rhel5.5下 安装11.2.0.4的rac.GI安装完了没问题. 可是 database software runInstaller安装时,全部的节点在图形化界面中看不到. 搜 ...
- 小强的HTML5移动开发之路(35)——jQuery中的过滤器详解
1.基本过滤选择器 :first :last :not(selector) :selector匹配的节点之外的节点 :even :偶数 :odd :奇数 :eq(index) :gt(index) : ...