`
thecloud
  • 浏览: 880769 次
文章分类
社区版块
存档分类
最新评论

《简明python教程》总结(五)-- 面向对象编程,输入/输出,异常

 
阅读更多
在python中一切皆为对象。
例: int为一个类,int i 中的 i为 int 类的对象/一个实例
类的属性: 方法和域。 域分两种类型:属于每个对象和属于类本身。分别称为 实例变量和 类变量。
类使用class关键字创建。类的域和方法被列在一个缩进块中。
self
类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调用这个方法的时候不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称是self
(相当于C++中的this指针)
调用时不需为给self赋值以及为何不需要给它赋值 原理:
假如有一个类称为MyClass和这个类的一个实例MyObject。当调用这个对象的方法MyObject.method(arg1, arg2)的时候,这会由Python自动转为MyClass.method(MyObject, arg1, arg2)——这就是self的原理了。
提醒:定义一个不需要参数的方法,同样还是得给这个方法定义一个self参数。
__int__方法
__init__方法在类的一个对象被建立时,马上运行。这个方法可以用来对对象做一些 初始化 。注意,这个名称的开始和结尾都是双下划线。(相当于C++中的构造函数)
两种类型的域
类的变量和对象的变量,它们根据是类还是对象 拥有 这个变量而区分。类的变量 由一个类的所有对象(实例)共享使用。
对象的变量 由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,即它们不是共享的,在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相关的。
__del__方法
同C++中的析构函数作用
Python中所有的类成员(包括数据成员)都是 公共的 ,所有的方法都是有效的 。
只有一个例外:如果你使用的数据成员名称以 双下划线前缀 比如__privatevar,Python的名称管理体系会有效地把它作为私有变量。
惯例:可以将欲作为私有变量的成员前加单下划线前缀,其他名称作为公共的
#!/usr/bin/python
# Filename: objvar.py
class Person:
'''Represents a person.'''
population = 0
def __init__(self, name):
'''Initializes the person's data.'''
self.name = name
print '
(Initializing %s)' % self.name
# When this person is created, he/she
# adds to the population
Person.population += 1
def __del__(self):
'
''I am dying.'''
print '
%s says bye.' % self.name
Person.population -= 1
if Person.population == 0:
print '
I am the last one.'
else:
print '
There are still %d people left.' % Person.population
def sayHi(self):
'
''Greeting by the person.
Really, that's all it does.'''
print 'Hi, my name is %s.' % self.name
def howMany(self):
'''Prints the current population.'''
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population
swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()
kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
Person.__doc__()
Person.howMany().__doc()
输出
$ python objvar.py
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul Kalam.
We have 2 persons here.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says bye.
I am the last one.
Represents a person.
Prints the current population.
分析:population 属于类的域,为各实例共享。 类的域,使用时通过 className.field调用,实例的域在函数定义时,通过self.field调用。
使用Person.__doc__和Person.sayHi.__doc__来分别访问类与方法的文档字符串
继承
面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过 继承 机制。
示例:
#!/usr/bin/python
# Filename: inherit.py
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
self.name = name
self.age = age
print '(Initialized SchoolMember: %s)' % self.name
def tell(self):
'''Tell my details.'''
print 'Name:"%s" Age:"%s"' % (self.name, self.age),
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print '(Initialized Teacher: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Salary: "%d"' % self.salary
class Student(SchoolMember):
'''Represents a student.'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print '(Initialized Student: %s)' % self.name
def tell(self):
SchoolMember.tell(self)
print 'Marks: "%d"' % self.marks
t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 22, 75)
print # prints a blank line
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students
输出
$ python inherit.py
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)
Name:"Mrs. Shrividya" Age:"40" Salary: "30000"
Name:"Swaroop" Age:"22" Marks: "75"
SchoolMember类被称为 基本类 或 超类 。而Teacher和Student类被称为 导出类 或 子类
输入/输出
文件与储存器
文件 (创建一个file类的对象来打开一个文件,分别使用file类的read、readline或write方法来恰当地读写文件。'w'--写,'r'--读,'a'--追加)
#!/usr/bin/python
# Filename: using_file.py
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'
''
f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close() # close the file
输出
$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
储存器
Python提供一个标准的模块,称为pickle。可以在一个文件中储存任何Python对象,之后又可以把它完整无缺地取出来。这被称为 持久地 储存对象。
还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。
示例(储存与取储存)
#!/usr/bin/python
# Filename: pickling.py
import cPickle as p
#import pickle as p
shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
输出
$ python pickling.py
['apple', 'mango', 'carrot']
分析:import cPickle as p 将模块cPickle命名为 p 优点:1. 方便更换模块,只需修改cPickle 2.方便方法调用 p.dump(),而非 cPickle.dump()
异常
try..except
引发异常
使用raise语句 引发 异常。需指明错误/异常的名称和伴随异常 触发的 异常对象。可以引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类。
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d'
% (x.length, x.atleast)
else:
print 'No exception was raised.'
输出
$ python raising.py
Enter something -->
Why did you do an EOF on me?
$ python raising.py
Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3
$ python raising.py
Enter something --> abc
No exception was raised.
try..finally
假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件,该怎么做呢?这可以使用finally块来完成。
示例:
#!/usr/bin/python
# Filename: finally.py
import time
try:
f = file('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
finally:
f.close()
print 'Cleaning up...closed the file'
输出:
正常运行
$ python finally.py
Programming is fun
When the work is done
Cleaning up...closed the file
运行中 ctrl+c中断/取消程序
$ python finally.py
Programming is fun
When the work is done
^Cclose the file
Traceback (most recent call last):
File "finally.py", line 12, in ?
time.sleep(2)
KeyboardInterrupt
分析:观察到KeyboardInterrupt异常被触发,程序退出。但是在程序退出之前,finally从句仍然被执行,把文件关闭
分享到:
评论

相关推荐

    简明 Python 教程.rar

    第11章面向对象的编程.87 简介.......87 self..........87 类...........88 II 简明 Python 教程 对象的方法........89 __init__方法.......90 类与对象的方法.91 继承.......95 概括.......98 第12章...

    简明 Python 教程 中文版

    Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程。Python简洁的语法和对动态输入的支持,再加上解释性语言的本质,使得它在大多数平台上的许多领域都是一个理想...

    简明python教程电子版 pdf高清版

    简明python教程电子版 pdf高清版,Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程。Python简洁的语法和对动态输入的支持,再加上解释性语言的本质,使得它在...

    简明python教程

    11. 面向对象的编程 简介 self 类 创建一个类 对象的方法 使用对象的方法 __init__方法 使用__init__方法 类与对象的变量 使用类与对象的变量 继承 使用继承 概括 12. 输入/输出 文件 使用文件 ...

    简明python教程(chm)

    11. 面向对象的编程 简介 self 类 创建一个类 对象的方法 使用对象的方法 __init__方法 使用__init__方法 类与对象的变量 使用类与对象的变量 继承 使用继承 概括 12. 输入/输出 文件 使用...

    简明Python教程4.pdf

    python新手入门书籍,内容非常简单,哪怕你从没学过编程,只要具有高中的数学知识,都能看懂。书中详细介绍每一行代码的含义,按照基础语法,循环判断,函数,面向对象依次讲解,脉络清晰

    Python-入门教程.pptx

    它有高效率的高层数据结构,能够简单、有效地实现面向对象编程。Python语法简洁,支持动态输入,是解释性语言。在大多数平台上,对于众多领域,Python都是一个理想的开发语言,特别适合于应用程序的 快速开发。 ...

    Python初学教程:《简明Python教程》

    Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程。Python简洁的语法和对动态输入的支持,再加上解释性语言的本质,使得它在大多数平台上的许多领域都是一个理想...

    python基础资料+教程+简明教程+学习资料

    教程包括了Python语言的基础语法、基本数据类型、控制结构、函数、模块、面向对象编程等方面的内容,可以帮助读者初步掌握Python的编程技能。在学习本教程之前,你需要具备一些基本的编程知识。例如,对于编程的概念...

    简明 Python 教程(中文)

    Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程。Python简洁的语法和对动态输入的支持,再加上解释性语言的本质,使得它在大多数平台上的许多领域都是一个理想...

    python学习资料教程

    Python源码剖析.pdf Python精要参考(第二版)_翻译.pdf Python网络数据采集.pdf Python计算机视觉编程 (Jan Erik Solem著) 中文pdf版.rar...简明Python教程.pdf 集体智慧编程-python算法应用.pdf 面向对象的思考过程.pdf

    简明Python教程

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

    Python编程入门.pptx

    它有高效率的高层数据结构,能够简单、有效地实现面向对象编程。 Python语法简洁,支持动态输入,是解释性语言。 在大多数平台上,对于众多领域,Python都是一个理想的开发语言,特别适合于应用程序的 快速开发。 ...

    简明 Python 教程

    Python是一种简单易学,功能强大的编程语言,它有高效率的高层数据结构,简单而有效地实现面向对象编程。Python简洁的语法和对动态输入的支持,再加上解释性语言的本质,使得它在大多数平台上的许多领域都是一个理想...

    python简明教程.chm

    11. 面向对象的编程 简介 self 类 创建一个类 对象的方法 使用对象的方法 __init__方法 使用__init__方法 类与对象的变量 使用类与对象的变量 继承 使用继承 概括 12. 输入/输出 文件 使用...

    Python学习教程:简明易懂的入门指南.pptx

    语法与基础知识 数据类型及操作 函数与面向对象编程 常用模块与库 目录 Python学习教程:简明易懂的入门指南全文共16页,当前为第2页。 01 语法与基础知识 Grammar and Fundamentals Python学习教程:简明易懂的...

    Python编程入门(适合于零基础朋友).pptx

    它有高效率的高层数据结构,能够简单、有效地实现面向对象编程。 Python语法简洁,支持动态输入,是解释性语言。 在大多数平台上,对于众多领域,Python都是一个理想的开发语言,特别适合于应用程序的 快速开发。 ...

    Python简明教程

    11. 面向对象的编程 简介 self 类 创建一个类 对象的方法 使用对象的方法 __init__方法 使用__init__方法 类与对象的变量 使用类与对象的变量 继承 使用继承 概括 12. 输入/输出 文件 使用文件 储存器 储存与...

Global site tag (gtag.js) - Google Analytics