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 ...
随机推荐
- SpringBoot 使用 @Value 从 YAML文件读取属性(转)
在 YAML中有如下配置 paypal: mode:live 在类中,通过 @Value属性读取 @Value("${paypal.mode}") private String m ...
- ios开发之Quartz2D 四:画饼图
#import "PieView.h" @implementation PieView - (void)drawRect:(CGRect)rect { // Drawing cod ...
- [Docker] Prune Old Unused Docker Containers and Images
In this lesson, we will look at docker container prune to remove old docker containers. We can also ...
- [Compose] 12. Two rules about Funtors
We learn the formal definition of a functor and look at the laws they obey. Any Functor should follo ...
- Bootstrapbutton
Bootstrap 提供了一些选项来定义button的样式,详细例如以下表所看到的: 下面样式可用于<a>, <button>, 或 <input> 元素上: 类 ...
- jquery-6 jquery属性选择器
jquery-6 jquery属性选择器 一.总结 一句话总结:jquery操作就是选择器加jquery对象的各种方法. 1.大量操作样式用什么方式? 大批量样式通过加类和减类完成 2.jquery中 ...
- PHP移动互联网开发笔记(5)——基础函数库
一.数学函数库 ● floor 舍一取整(向下取整) float floor (float $value); <?php echo(floor(0.60)."<br>&qu ...
- 【矩阵】概念的理解 —— span、基
span:全部列向量的线性组合构成的集合: span[a1,-,an]={y∈Rm|y=∑k=1nckak}=S 注:ak∈Rm,共 n 个列向量: 集合 S 可以有不同的一组基,但是基中向量的个数是 ...
- Opencv Surf算子中keyPoints,描述子Mat矩阵,配对向量DMatch里都包含了哪些好玩的东东?
Surf算法是一把牛刀,我们可以很轻易的从网上或各种Opencv教程里找到Surf的用例,把例程中的代码或贴或敲过来,满心期待的按下F5,当屏幕终于被满屏花花绿绿的小圆点或者N多道连接线条霸占时,内心 ...
- js进阶 10-1 JQuery是什么
js进阶 10-1 JQuery是什么 一.总结 一句话总结: 1.两种引用jquery的方法? 可以在线jquery和本地jquery两种 2.jquery主要好处? 浏览器兼容问题 二.js进阶 ...