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 '
相关文档:
Python代码优化--少打字小技巧
说明:增加代码的描述力,可以成倍减少你的LOC,做到简单,并且真切有力
观点:少打字=多思考+少出错,10代码行比50行更能让人明白,以下技巧有助于提高5倍工作效率
1. 交换变量值时避免使用临时变量:(cookbook1.1)
老代码:我们经常很熟练于下面的代码
temp = x
x = y
y = ......
# 005
# 在Python中给变量赋值时不需要声明数据类型
i = 33
print i
# 可以这样做的原因是Python把程序中遇到的任何东西都看成是对象(连int也不例外)
# 这样,在使用对象时,编译器会根据上下文的环境来调用对象自身的方法完成隐式的转换
# 你甚至可以把程序写成这样
print 3 * 'haha '
# 但若写成这样编译器就会报错 ......
模块这东西好像没什么好讲的,无非是保存一份文件,然后在另一份文件中用import 和from ** import **(*)就行了。
这一章主要讲到了细节,导入模块Python里面是什么处理的,import 和 from ** import **有什么不一样。还有就是增加了reload()这个函数的使用说明。
以前看到哪里说尽量使用import而不要使用from ** import * ......
源代码下载:下载地址在这里
# 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 ......
源代码下载:下载地址在这里
# 035
class Person:
population = 0 #这个变量是属于整个类的
def __init__(self, name):
self.name = name
print '初始化 %s' % self.name
Person.population += 1
# end of def
def __del__(self):
print '%s says bye.' % self. ......