廖雪峰python网站
#if els
# -*- coding: utf-8 -*-
#list是一种有序的集合,可以随时添加和删除其中的元素。
'''
classmates=['a','b','c',['x','y']]
classmates.append('Adam')
classmates.insert(1,'jack')
classmates.pop()
classmates.pop(1)
print(classmates)
print(len(classmates))
print(classmates[0]+','+classmates[1]+','+classmates[2])
print(','+classmates[-2]+','+classmates[-3])
print(classmates[-1])
print(classmates[-1])
'''
#tuple叫元组,tuple一旦初始化就不能修改
'''
classmates=('a','b','c')
print(classmates)
classmates=(1,)
print(classmates)
t=('a', 'b', ['A', 'B'])
t[2][0]='x'
t[2][1]='y'
print(t)
'''
#列表生成式
'''
t=list(range(1,11))
print(t)
L=[]
for x in range(1,11):
L.append(x*x)
print(L)
L1=[x*x for x in range(1,11)]
print(L1)
#写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来
d = {'x': 'A', 'y': 'B', 'z': 'C' }
L2=[k+'='+v for k,v in d.items()]
'''
#斐波那契数列
'''
def fib(x):
a,n,c=0,0,1
while n<x:
yield c
a,c=c,a+c
n=n+1
return c
for n in fib(6):
print(n)
'''
#杨辉三角
'''
def triangles(n):
s1=[1];
yield s1;
s=[1];
while len(s)<=n:
s=[1]+[s[a-1]+s[a] for a in range(1,len(s))]+[1]
yield s
return s
n = 0
results = []
for t in triangles(9):
print(t)
'''
#map
'''
import array
def f(x):
la=len(x)-1
return x[0].upper()+x[1:].lower()
r=map(f,['adam', 'LISA', 'barT'])
print(list(r))
'''
#reduce
'''
from functools import reduce
def prod(L):
def f(x,y):
return x*y
r=1
while r<len(L):
L[r]=reduce(f,[L[r-1],L[r]])
r=r+1
return L[-1]
print(prod([3, 5, 7, 9]))
'''
#map+reduce
'''
from functools import reduce
str='123.154'
def str2float(s):
n=s.index('.')
s1=reduce(lambda x,y:x*10+y,map(int,s[:n]))
s2=reduce(lambda x,y:x*10+y,map(int,s[n+1:]))
return s1+s2/10**len(s[n+1:])
print(str2float(str))
'''
#filter
'''
def is_odd(n):
return n % 2 == 1
print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))
def not_empty(s):
return s and s.strip()
print(list(filter(not_empty, ['A', '', 'B', None, 'C', ' '])))
def _not_divisible(n):
return lambda x:x%n>0
print(list(filter(_not_divisible(3),[1,2,3,4,5,6,7])))
'''
#打印素数
'''
def _odd_iter():
n=1
while True:
n=n+2
yield n
def _not_divisible(n):
return lambda x:x%n>0
def primes():
yield 2
it = _odd_iter()
while True:
n=next(it)
yield n
it = filter(_not_divisible(n),it)
# 打印1000以内的素数:
for n in primes():
if n < 1000:
print(n)
else:
break
'''
#反序和正序相等
'''
def is_palindrome(n):
return str(n)==str(n)[::-1]
# 测试:
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
print('测试成功!')
else:
print('测试失败!')
'''
#排序算法
'''
print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True))
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0].lower()
L2=sorted(L,key=by_name)
print(L2)
def by_score(t):
return -t[1]
L2=sorted(L,key=by_score)
print(L2)
'''
#返回函数/返回值
'''
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum
f=lazy_sum(1,3,5,9)
print(f)
print(f())
'''
#匿名函数
'''
print(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])))
f = lambda x: x * x
print(f)
print(f(5))
'''
#装饰器
#模块
'''
' a test module '
__author__ = 'Michael Liao'
import sys
def test():
args = sys.argv
if len(args)==1:
print('Hello, world!')
elif len(args)==2:
print('Hello, %s!' % args[1])
else:
print('Too many arguments!')
if __name__=='__main__':
test()
'''
#开闭原则,继承
'''
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
class Cat(Animal):
def run(self):
print('Cat is running...')
def run_twice(animal):
animal.run()
animal.run()
dog=Dog()
cat=Cat()
print(run_twice(dog))
print(run_twice(cat))
'''
#获取对象信息
#print(type(123))
'''
import types
def fn():
pass
print(type(fn)==types.FunctionType)
print(type(abs)==types.BuiltinFunctionType)
print(type(lambda x:x)==types.LambdaType)
print(type(x for x in range(10))==types.GeneratorType)
'''
'''
class Animal(object):
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
a=Animal()
d=Dog()
print(isinstance(d,Dog))
print(isinstance(d,Animal))
print(isinstance('a',str))
'''
#判断是否是某些类型其中1种
'''
print(isinstance([1, 2, 3], (list, tuple)))
'''
#如果要获得一个对象的所有属性和方法,可以使用dir()函数
'''
print(dir('ABC'))
'''
#测试对象得属性
'''
class MyObject(object):
def __init__(self):
self.x=9
def power(self):
return self.x * self.x
obj=MyObject()
print(hasattr(obj,'x'))
print(obj.x)
print(setattr(obj,'y',19)
print(hasattr(obj,'y'))
print(getattr(obj,'y'))
'''
#实例属性
'''
class Student(object):
pass
s = Student()
s.name = 'Michael'
print(s.name)
'''
#实例方法
'''
from types import MethodType
class Student(object):
pass
s = Student()
def set_age(self, age):
self.age = age
s.set_age = MethodType(set_age, s)
s.set_age(25)
print(s.age)
'''
#class绑定方法
'''
class Student(object):
pass
def set_score(self, score):
self.score = score
Student.set_score = set_score
s=Student()
s.set_score(100)
print(s.score)
'''
#限制对象的方法,对子类不限制
'''
class Student(object):
__slots__=('name','age')
s=Student()
s.name='Mike'
s.age=25
class GraduateStudent(Student):
pass
g=GraduateStudent()
g.score=99
'''
#将方法变成属性调用(常用于getter,setter),@property修饰getter,@score.setter,修饰setter
'''
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
s=Student()
s.score=60
print(s.score)
'''
#MixIn继承
'''
class Animal(object):
pass
# 大类:
class Mammal(Animal):
pass
class Bird(Animal):
pass
# 各种动物:
class Parrot(Bird):
pass
class Ostrich(Bird):
pass
class RunnableMixIn(object):
def run(self):
print('Running...')
class Flyable(object):
def fly(self):
print('Flying...')
class Dog(Mammal, RunnableMixIn):
pass
class Bat(Mammal, Flyable):
pass
'''
#一些方法
#__str__ 类似toString()
'''
class Student(object):
def __init__(self, name):
self.name = name
def __str__(self):
return 'Student object (name: %s)' % self.name
print(Student('Michael'))
'''
#__iter__ 类似迭代器
'''
class Fib(object):
def __init__(self):
self.a,self.b=0,1
def __iter__(self):
return self
def __next__(self):
self.a,self.b=self.b,self.a+self.b
if self.a>100000:
raise StopIteration()
return self.a
for n in Fib():
print(n)
'''
#__getitem__ 该方法可以用下标取出迭代器的内容
'''
class Fib(object):
def __getitem__(self,n):
if isinstance(n,int):
a,b=1,1
for x in range(n):
a,b=b,a+b
return a
if isinstance(n,slice):
start=n.start
stop=n.stop
if start is None:
start=0
a,b=1,1
L=[]
for x in range(stop):
if x>=start:
L.append(a)
a,b=b,a+b
return L
f=Fib()
print(f[5:10])
'''
#__getattr__ 在类中设置该方法,用来调用不存在的属性
'''
class Student(object):
def __init__(self):
self.name='Michael'
def __getattr__(self,attr):
if attr=='score':
return 99
s=Student()
print(s.name)
print(s.score)
'''
#不允许出现不存在的属性
'''
class Student(object):
def __init__(self):
self.name='Michael'
def __getattr__(self,attr):
if attr=='score':
return lambda:25
raise AttributeError('\'Student\' object has no attribute \'%s\'' % attr)
s=Student()
print(s.name)
print(s.score())
print(s.test)
'''
#__call__给实例定义的方法
'''
class Student(object):
def __init__(self,name):
self.name=name
def __call__(self):
print('My name is %s.' % self.name)
s=Student('Michael')
print(s())
'''
#callable()对象是否可调用
'''
class Student(object):
pass
a=callable(Student())
print(a)
a=callable(max)
print(a)
a=callable([1,2,3])
print(a)
a=callable(None)
print(a)
'''
#枚举
'''
from enum import Enum
Month = Enum('Month',('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'))
for name,member in Month.__members__.items():
print(name,'=>',member,',',member.value)
'''
'''
from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0 # Sun的value被设定为0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
day1=Weekday.Mon
print(day1)
Weekday.Mon
print(Weekday.Tue)
print(Weekday['Tue'])
print(Weekday.Tue.value)
print(day1==Weekday.Mon)
print(Weekday(1))
for name,member in Weekday.__members__.items():
print(name, '=>', member)
'''
'''
@unique
class Gender(Enum):
Male=0
Female=1
class Student(object):
def __init__(self,name,gender):
self.name=name
if type(gender)==Gender:
self.gender=gender
else:
raise AttributeError('gender is wrong')
'''
'''
class Hello(object):
def hello(self,name='world'):
print('Hello,%s.',% name)
'''
#try except finally 异常
'''
def main():
try:
print('try....')
r=10/'a'
print('result:',r)
except ZeroDivisionError as e:
print('ZeroDivisionError:',e)
except ValueError as e:
print('ValueError:',e)
except TypeError as e:
print('typeError')
else:
print('no error')
finally:
print('finally...')
main()
print('END')
'''
#logging日志
'''
import logging
def foo(s):
return 10/int(s)
def bar(s):
return foo(s)*2
def main():
try:
bar('0')
except Exception as e:
logging.exception(e)
main()
print('END')
'''
#创建异常
'''
class FooError(ValueError):
pass
def foo(s):
n=int(s)
if n ==0:
raise FooError('invalid value:%s' % s)
return 10/n
print(foo('0'))
'''
#调试代码 assert
'''
def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
def main():
foo('0')
main()
'''
#logging 不会抛出错误,但会输出到文件
'''
import logging
logging.basicConfig(level=logging.INFO)
s='0'
n=int(s)
logging.info('n=%d' % n)
print(10/n)
'''
#单步调试 pdb python -m pdb XXX.py
'''
s='0'
n=int(s)
print(10/n)
'''
#端点调试 pdb.set_trace()
'''
import pdb
s='0'
n=int(s)
pdb.set_trace()
print(10/n)
'''
#单元测试 unittest
'''
import unittest
class Dict(dict):
def __init__(self,**kw):
super().__init__(**kw)
def __getattr__(self,key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" %key)
def __setattr__(self,key,value):
self[key]=value
class TestDict(unittest.TestCase):
def test_init(self):
d=Dict(a=1,b='test')
self.assertEqual(d.a,1)
self.assertEqual(d.b,'test')
self.assertTrue(isinstance(d,dict))
def test_key(self):
d=Dict()
d['key']='value'
self.assertEqual(d.key,'value')
def test_attr(self):
d=Dict()
d.key='value'
self.assertTrue('key' in d)
self.assertEqual(d['key'],'value')
def test_keyerror(self):
d=Dict()
with self.assertRaises(KeyError):
value=d['empty']
def test_attrerror(self):
d=Dict()
with self.assertRaises(AttributeError):
value=d.empty
if __name__=='__main__':
unittest.main()
'''