Python入门的36个例子 之 32
源代码下载:下载地址在这里
A Byte Of Python
中关于继承有这样的文字:
Suppose you want to write a program which has to keep track of the
teachers and students in a college. They have some common
characteristics such as name, age and address. They also have specific
characteristics such as salary, courses and leaves for teachers and,
marks and fees for students.
You can create two independent classes for each type and process them
but adding a new common characteristic would mean adding to both of
these independent classes. This quickly becomes unwieldy.
A better way would be to create a common class called SchoolMember and
then have the teacher and student classes inherit from this class i.e.
they will become sub-types of this type (class) and then we can add
specific characteristics to these sub-types.
这段文字很简单,我开始也这么认为。但当我不小心第二次读这本书的时候才领会到这些文字所要传达的深意。
继承在我看来,或者说在以前的我看来,是为了代码重用,是的,我现在也这么认为。但,对于为什么继承有利于代码重用我却有了不同的理解。以前的理解
是这样的:我先写一个类,以后需要扩展这个类的功能的时候就先继承它,然后再添加一些方法等。这样就算是代码重用了。现在我有了新的理解:继承的本质是将共性和个性分离。
在设计类的一开始,我们甚至已经明白了这个类在以后的用处以及会被如何地继承,我们将共性和个性分开,是我们对整个系统的修改变得简单。说的更明白一点,与其说“继承机制”是为了代码重用,不如说是为了代码维护。在计算机世界,无数事实告诉我们,分离的东西是好的。
# 036
class SchoolMember:
def __init__(self, name, age):
self.name = name
self.age = age
print '初始化%s' % self.name
# end of def
def tell(self):
print '名字:%s 年龄:%s' % (self.name, self.age)
# end of def
# end of class
class Teacher(SchoolMember):
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age) # Python不会自己调用基本类的构造函数,我们得自己调用。
self.salary = salary
print '
相关文档:
模块这东西好像没什么好讲的,无非是保存一份文件,然后在另一份文件中用import 和from ** import **(*)就行了。
这一章主要讲到了细节,导入模块Python里面是什么处理的,import 和 from ** import **有什么不一样。还有就是增加了reload()这个函数的使用说明。
以前看到哪里说尽量使用import而不要使用from ** import * ......
源代码下载:下载地址在这里
# 022
listNum1 = [1, 3]
listNum2 = [2, 4]
listStr1 = ['a', 'c']
listStr2 = ['b', 'd']
# 列表的合并
list1 = listNum1 + listStr1
for ele in list1:
print ele
print '\n'
# 判断列表中是否包含某元素
print 'b' in list1
print 1 in list1
# 删除某个元素
for ele in ......
# 027
toolName = 'Google'
if toolName.startswith('Go'):
print 'The tool\'s name starts with \"Go\".'
if 'oo' in toolName:
print 'The tool\'s name contains the stirng "oo".'
print toolName.find('gl') # 返回首次出现“gl”字符串的索引
if toolName.find('Baidu ......
源代码下载:下载地址在这里
# 034
class Person:
def __init__(self, name):
self.name = name # 这一句中第一个name是类中包含的域,第二个name是传进来的参数
# end of def
def sayHello(self):
print 'Hello!'
# end of def
# end of class
p = Person('Ning')
print p.nam ......