class GenericDisplay:
def gatherAttrs(self):
attrs = '\n'
for key in self.__dict__:
attrs += '\t%s=%s\n' % (key, self.__dict__[key])
return attrs
def __str__(self):
return '' % (self.__class__.__name__, self.gatherAttrs())
class Person(GenericDisplay):
def __init__(self, name, age):
self.name = name
self.age = age
def lastName(self):
return self.name.split()[-1]
def birthDay(self):
self.age += 1
class Employee(Person):
def __init__(self, name, age, job=None, pay=0):
Person.__init__(self, name, age)
self.job = job
self.pay = pay
def birthDay(self):
self.age += 2
def giveRaise(self, percent):
self.pay *= (1.0 + percent)
if __name__ == '__main__':
bob = Person('Bob Smith', 40)
print bob
print bob.lastName()
bob.birthDay()
print bob
sue = Employee('Sue Jones', 44, job='dev', pay=100000)
print sue
print sue.lastName
sue.birthDay()
sue.giveRaise(.10)
print sue
【例035】根据给定的年月日以数字方式打印出日期(February 27th, 2015)
复制代码 代码如下:
# coding = UTF-8
#根据给定的年月日以数字形式打印出日期
months = [
'January' ,
'February',
'March' ,
'April' ,
'May' ,
'June' ,
'July' ,
'August' ,
'September',
'October' ,
'November' ,
'December'
]
#以1~31的数字作为结尾的列表
endings = ['st','nd','rd'] + 17 * ['th'] + \
['st','nd','rd'] + 07 * ['th'] + \
['st']
year = raw_input('Year: ')
month = raw_input('Month(1-12): ')
day = raw_input('Day(1-31): ')
month_number = int(month)
day_number = int(day)
#月份和天数减1来获得正确的索引
month_name = months[month_number - 1]
ordinal = day + endings[day_number - 1]
print month_name + ' ' + ordinal + ', ' + year
#输出结果
>>>
Year: 2015
Month(1-12): 2
Day(1-31): 27
February 27th, 2015
【例036】在居中的盒子里打印一条语句
复制代码 代码如下:
sentence = raw_input("Sentence: ")
screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width) // 2
print
print ' '*left_margin + '+' + '-'*(box_width-4) + '+'
print ' '*left_margin + '| ' + ' '*(text_width) +' |'
print ' '*left_margin + '| ' + sentence +' |'
print ' '*left_margin + '| ' + ' '*(text_width) +' |'
print ' '*left_margin + '+' + '-'*(box_width-4) + '+'
print
#输出结果
>>>
Sentence: Welcome To Beijing!
+---------------------+
| |
| Welcome To Beijing! |
| |
+---------------------+
【例037】简单小数据库验证
复制代码 代码如下:
database = [
['Bob', '1234'],
['Tom', '2345'],
['Foo', '1478']
]
usr = raw_input('Enter username: ')
pwd = raw_input('Enter password: ')
if [usr, pwd] in database:
print 'Access Granted!'
else:
print 'Access Deny!'
【例038】使用给定的宽度打印格式化后的价格列表
复制代码 代码如下:
width = input('Please enter width: ')
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
format = '%-*s%*.2f'
print '=' * width
print header_format % (item_width, 'Item', price_width, 'Price')
print '-' * width
print format % (item_width, 'Apples', price_width, 0.4)
print format % (item_width, 'Sweets', price_width, 0.5)
print format % (item_width, 'Pepper', price_width, 12.94)
print format % (item_width, 'Tender', price_width, 42)
print '-' * width
输出格式:
复制代码 代码如下:
>>>
Please enter width: 30
==============================
Item Price
------------------------------
Apples 0.40
Sweets 0.50
Pepper 12.94
Tender 42.00
------------------------------
【例039】遍历两个对应列表
复制代码 代码如下:
names = ['Alice', 'Bob' , 'Cherry', 'David']
numbers = ['0000' , '1111', '2222' , '3333' ]
for index,name in enumerate(names):
print '%-7s=> %s' % (name, numbers[index])
#输出结果
>>>
Alice => 0000
Bob => 1111
Cherry => 2222
David => 3333
当然也可以采用如下通常的做法:
复制代码 代码如下:
names = ['Alice','Bob', 'John', 'Fred']
ages = [27, 23, 31, 29]
for i in range(len(ages)):
print names[i],' is ', ages[i], ' years old!'
#输出结果:
>>>
Alice is 27 years old!
Bob is 23 years old!
John is 31 years old!
Fred is 29 years old!
【例040】对存储在小字典中数据进行查询
复制代码 代码如下:
peoples = {
'Alice':{
'phone' : '0948',
'address' : 'aaaa'
},
'Wendy':{
'phone' : '4562',
'address' : 'bbbb'
},
'David':{
'phone' : '4562',
'address' : 'bbbb'
}
}
#字典使用人名作为键。每个人用另外一个字典来表示,其键'phone'和'addr'分别表示他们的电话号码和地址
labels = {
'phone' : 'phone number',
'address' : 'address'
}
#针对电话号码和地址使用描述性标签,会在打印输出时用到。
key = ''
name = raw_input('Name: ')
if name in peoples:
request = raw_input('Enter (p) or (a): ')
if request == 'p':
key = 'phone'
elif request == 'a':
key = 'address'
else:
print 'Please input p(phone) an a(address)!'
print "%s's %s is %s" % (name, labels[key],peoples[name][key])
else:
print 'Not Found!'
或者使用字典的get()方法,更好些。完整代码如下:
复制代码 代码如下:
#字典使用人名作为键。每个人用另外一个字典来表示,其键'phone'和'addr'分别表示他们的电话号码和地址
peoples = {
'Alice':{
'phone' : '0948',
'address' : 'aaaa'
},
'Wendy':{
'phone' : '4562',
'address' : 'bbbb'
},
'David':{
'phone' : '4562',
'address' : 'bbbb'
}
}
#针对电话号码和地址使用描述性标签,会在打印输出时用到。
labels = {
'phone' : 'phone number',
'addr' : 'address'
}
name = raw_input('Name: ')
#查找电话号码还是地址?
request = raw_input('Phone number (p) or address (a)? ')
#查找正确的键
key = request #如果请求即不是p也不是a
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
#使用get()函数提供默认值
person = peoples.get(name,{})
label = labels.get(key, key)
result = person.get(key, 'not available')
print "%s's %s is %s." % (name, label, result)
【例041】字典格式化字符串例子
复制代码 代码如下:
template='''''
%(title)s
%(text)s
'''
data = {'title':'My Home Page','text':'Welcome to my home page!'}
print template % data
#输出结果:
>>>
My Home Page
Welcome to my home page!
【例042】需找100以内的最大平方数
复制代码 代码如下:
from math import sqrt
#从100开始往下找,找到即停止,最大为: 81
for n in range(99, 0, -1):
root = sqrt(n)
if root == int(root):
print n
break
【例043】用while/True, break控制输入
复制代码 代码如下:
while True: #一直进行下去,除非break
word = raw_input('Please Enter a word: ')
if not word: break #输入为空的话,中断循环
print 'The word was: ' + word
【例044】将两个列表中首字母相同的提取出来
复制代码 代码如下:
#将两个列表中首字母相同的罗列在一起
girls = ['alice', 'bernice', 'clarice']
boys = ['chris', 'arnold', 'bob']
#列表推导:
print [b+'+'+g for b in boys for g in girls if b[0] == g[0]]
#输出结果:
>>>
['chris+clarice', 'arnold+alice', 'bob+bernice']
【例045】斐波那契数列求指定数字的列表
复制代码 代码如下:
def fibs(x):
fibs = [0, 1] # 初始值
for i in range(x):
# fibs[-2]+fibs[-1]:最新一个值是前面两个值之和
# 并用append方法将其添加在后面
fibs.append(fibs[-2]+fibs[-1])
print fibs
if __name__=='__main__':
num = input('How many Fibonacci numbers do you want? ')
fibs(num)
或者用普通方法实现:
复制代码 代码如下:
>>> def fib(max):
n, a, b = 0, 0, 1
tmp_list = []
while n
tmp_list.append(a)
a, b = b, a+b
n += 1
return tmp_list
>>> fib(8)
[0, 1, 1, 2, 3, 5, 8, 13]
【例046】写一个自定义列表类,让它支持尽可能多的支持操作符号
复制代码 代码如下:
class MyList:
def __init__(self, start):
self.wrapped = [] # Make sure it's a list here
for x in start:
self.wrapped.append(x)
def __add__(self, other):
return MyList(self.wrapped + other)
def __mul__(self, time):
return MyList(self.wrapped * time)
def __getitem__(self, offset):
return self.wrapped[offset]
def __len__(self):
return len(self.wrapped)
def __getslice__(self, low, high):
return MyList(self.wrapped[low:high])
def append(self, node):
self.wrapped.append(node)
def __getattr__(self, name): # Other members: sort/reverse/etc
return getattr(self.wrapped, name)
def __repr__(self):
return repr(self.wrapped)
if __name__ == '__main__':
x = MyList('spam')
print x
print x