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 '
相关文档:
二元运算符及其对应的特殊方法
二元运算符
特殊方法
+
__add__,__radd__
-
__sub__,__rsub__
*
__mul__,__rmul__
/
__div__,__rdiv__,__truediv__,__rtruediv__
//
__floordiv__,__rfloordiv__
%
__mod__,__rmod__
**
__pow__,__rpow__
<<
__lshift__,__rlshift__
>>
_ ......
# 004
# 利用三引号(''' or """)可以指示多行字符串
print '''line1
line2
line3'''
# 另外,你还可以在三引号中任意使用单引号和双引号
print ''' "What's up? ," he replied.'''
# 否则,你好使用转义符来实现同样的效果
# 还是使用三引号好,不然就破坏了视觉美了
print ' \"Wha ......
# 015
# 默认参数的本质是:
# 不论你是否提供给我这个参数,我都是要用它,
# 那么我就要想好在你不向我提供参数的时候我该使用什么。
# 或者,这样来理解:
# 有一些参数在一般情况下是约定俗成的,
# 但,在极少情况下会有一些很有个性的人会打破传统而按照自己的习惯来做事
def theFirstDayInAWeek(theDay = 'Sunda ......
源代码下载:下载地址在这里
# 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 ......
源代码下载:下载地址在这里
# 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. ......