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 '
相关文档:
代码很简单,不到5k行。但是思路挺好的,改成non-blocking了之后效率就是能提高不少,特别是考虑到现代的web app都需要和其他的
HTTP服务器通信,blocking的代价太大了。 Tornado is an open source version of the scalable, non-blocking web server and tools that power FriendFeed. The FriendFeed application ......
源代码下载:下载地址在这里
# 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 ......
源代码下载:下载地址在这里
# 023
# Tuple(元素组)是不可变的列表
tuple1 = (1, 2, 3)
print tuple1
tuple2 = (tuple1, 4, 5, 6) # 一个元素组可以作为另外一个元素组的元素
print tuple2 # 并且能够在存储的时候保持原始的逻辑关系
for ele in tuple2:
print ele
print '\n'
for ele in tuple2[0]:
pr ......
源代码下载:下载地址在这里
# 033
class Person:
age = 22
def sayHello(self): # 方法与函数的区别在于需要一个self参数
print 'Hello!'
# end of def
# end of class # 这是我良好的编程风格
p = Person()
print p.age
p.sayHello()
output:
22
Hello! ......