python的高级特性
切片
- 字符串,列表,元组是有序的序列,可以执行切片操作;
- 集合和字典是无序的,不能通过下标进行切片;
s[m:n:x]
迭代
- 迭代: 遍历目标变量中的每一个元素的过程; 只要可以通过for循环遍历的对象都是可迭代,可迭代对象通过for循环遍历;
from collections import Iterable
In [10]: isinstance(1,int)
Out[10]: True
In [11]: isinstance(1,Iterable)
Out[11]: False
In [12]: isinstance("hello",Iterable)
Out[12]: True
In [13]: isinstance({},Iterable)
Out[13]: True
In [14]: isinstance({"a":"1"},Iterable)
Out[14]: True
In [15]: isinstance({1,2,3},Iterable)
Out[15]: True
- 默认情况下,字典遍历是遍历字典的key值;
In [16]: d = {"ftp":21,"ssh":22}
In [17]: for i,j in d.items():
....: print i,j
....:
ftp 21
ssh 22
In [18]: for i in d:
....: print i
....:
ftp
ssh
In [21]: for host,port in [("server1",80),("server2",8080)]:
print host + ":" + str(port)
....:
server1:80
server2:8080
列表生成式
- 生成列表的一个式子;list comprehension.
格式: [i.lower() for i in l]
简单的列表生成式
[i**2 for i in range(1,10)]
[abs(i) for i in range(1,10)]
[fun(i) for i in range(1,11)]嵌套if语句
[i for i in range(1,10) if isprime(i)]嵌套for循环
“abc” “123”
[i+j for i in “abc” for j in “123”]
[service+”:”+str(port) for service,port in d.items()]
练习:
l = [“westos”,18,”red”],将所有的字符串变成大写并输出;
[i.upper() for i in l if isinstance(i,str)]
[i.upper() for i in l if type(i)==str]
生成器
通过列表生成式可以修改为生成器;
优势:
1). 节省内存空间;
2). 可以一边循环一边计算;
生成器的创建
1). 通过列表生成式可以修改为生成器;
2). 关键字yield,函数中有yield时,这个函数执行返回结果是一个生成器;生成器的查看:
1). g.next()
2). for循环
函数式编程
内置的高阶函数
map函数,map(函数, 序列),将传入的函数作用于列表中的每一个元素,返回一个列表;
reduce函数,reduce(函数, 序列),将函数的执行结果相加.
reduce(f,range(1,11)) = f(f(f(1,2),3),4)filter函数,filter(函数, 序列),将函数作用于序列的每一个元素,将满足条件的返回;
sorted函数,sorted(序列,函数),按照自定义格式排序;
装饰器(器,就是函数,装饰器就是用来装饰函数的函数)
普通的函数:
def 函数名(形参): # 变量名
函数体
return 变量|常量
print 函数名(实参)
匿名函数
lambda 形参 : 返回值
面向对象编程
面向过程: 程序从上至下依次执行;
CS:
role: 警察,恐怖分子,人质
role1
name=”唐浩”
role=”人质”
life_value=100
role2
name=”豆鹏强”
role=”恐怖分子”
weapon=”AK47”
life_value=100
money=16000
role3
name=”严贵清”
role=”警察”
weapon=”M4”
life_value=100
money=16000
class Police:
pass
class Kongbu:
pass
class Renzhi:
pass
什么是面向对象?
类 ===== 建房子的图纸 (三室一厅,两室一厅…….)
对象===== 实际建出来的房子(门牌号)
class ThreeRoom:
pass
seven_zero_one = ThreeRoom()
seven_zero_one.live()
seven_zero_one.clean()
面向对象的三个特性
封装,继承,多态
举个栗子
装饰器
# 装饰器: 装饰函数的一个函数,
#
# 该方法实现了装饰器的功能,但是调用函数的方式发生了改变;
def dtimer(fun):
def timer(*args,**kwargs): # 高阶函数 #args = (1,2,3,4)
start_time = time.time()
fun(*args,**kwargs) # args =(1,2,3,4), 解包*(1,2,3,4)
stop_time = time.time()
return "run %s" % (stop_time - start_time)
return timer # 返回的是timer的地址,要执行该函数需要timer()
@dtimer # fun1 = dtimer(fun1)
def fun1(*args,**kwargs):
print "in the fun1....."
print args
time.sleep(1)
def fun2():
print "in the fun2....."
time.sleep(0.5)
print fun1(1,2,3,4)
# print timer(fun2)
闭包
# 闭包: 函数里面嵌套函数,并且外面函数的返回值是一个函数;
#
def lazy_sum(*args):
def add():
return sum(args)
return add # add函数
a = lazy_sum(1,2,3,4)
print a #a实质是add函数
print a()
def add(x, y):
c = x + y
return c # c=3
a = add(1, 2)
print a
# 高阶函数:把函数名当作实参传入函数的函数称为高阶函数;
print map(add, range(1, 10))
类
类的第一个特性:封装
# 类的第一个特性:封装
# - self实质上是什么? 实例化出来的对象
# - 封装是把实例化的对象和它的属性封装在一起,便于其他函数的使用;
# - 访问对象属性的两种方式:
# self.name
# tianfeng.name
class People(object): # 类
def __init__(self,name,age): # 构造函数
self.name = name # 属性
self.age = age
def eat(self): #方法
print " %s 正在吃辣条....." %(self.name)
def echo_self(self):
print self
tianfeng = People("田峰",18) # 通过类实例化出来的对象
print tianfeng
tianfeng.echo_self()
# print tianfeng.name
# print tianfeng.age
# tianfeng.eat()
# wangweibo= People("王伟波",18) # 通过类实例化出来的对象
# print wangweibo
# wangweibo.echo_self()
类的第二个特性:继承
# 类的第二个特性:继承
class People(object): # 类
def __init__(self, name, age): # 构造函数,在实例化对象时自动运行
self.name = name # 属性
self.age = age
def eat(self): # 方法
print " %s 正在吃辣条....." % (self.name)
def echo_self(self):
print self
class Animal(object):
def __init__(self, name, age):
self.name = name # 属性
self.age = age
def eat(self): # 方法
print " %s 正在吃辣条....." % (self.name)
def drink(self):
print "%s is drinking...." % (self.name)
class Student(People, Animal): # Student是子类/派生类, People是父类/基类
pass
tianfeng = People("田峰", 18)
tianfeng.eat()
fentiao = Student("粉条", 18)
fentiao.eat()
fentiao.drink()
类的优先级
# 当你的类是新式类,多继承的算法是广度优先;
# 当你的类是经典类,多继承的算法是深度优先;
class D(object): # 新式类
# class D: # 经典类
def eat(self):
print "D eating"
pass
class C(D):
# def eat(self):
# print "C eating"
pass
class B(D):
def run(self):
print "runing"
# def eat(self):
# print "B eating"
class A(B, C):
pass
a = A()
a.eat()
类的第三个特性:多态
# 类的第三个特性:多态
class Animal(object):
def __init__(self,name):
self.name = name
def eat(self):
print "%s 正在吃......" %(self.name)
class Cat(Animal):
def __init__(self,name,kind):
# Animal.__init__(self,name) # self.name = name
super(Cat, self).__init__(name)
self.kind = kind
def eat(self):
print "%s 正在吃猫粮......" %(self.name)
class Dog(Animal):
# def __init__(self,name,age):
#
def eat(self):
print "%s 正在吃狗粮......" % (self.name)
c = Cat("fentiao","美短")
c.eat()
# d = Dog("fentiaotiao")
# d.eat()
if __name__ == "__main__":
pass
类的私有属性
# 类的私有属性
class People(object):
def __init__(self, name, money):
self.name = name
self.__money = money # python内部将self.__money给它重命名为_类名__money
def get_money(self):
return "%s 拥有 %d 美元资产" % (self.name, self.__money)
def eat(self):
print "%s 正在吃......" % (self.name)
p = People("豆鹏强", 1000000)
print p.name
print p.get_money()
p.__money = 100
print p.__money
print p.get_money()
p._People__money = 100
print p.get_money()
class Date(object):
def __init__(self,year, month,day):
self.year = year
self.month = month
self.day = day
def echo_date(self):
print "Year:",self.year
print "Month:",self.month
print "Day:",self.day
@classmethod
def from_str(cls,s): # class,类方法的第一个参数是类本身,cls = Date
year, month, day = map(int, s.split("-"))
d = cls(year,month,day) # d = Date(year,month,day)
return d # 对象
@staticmethod
def is_date_legal(s): # 静态方法,第一个参数既不是对象,也不是类本身,
year, month, day = map(int, s.split("-"))
return year >= 1970 and 0 < month <= 12 and 0 < day <= 31
# d = Date(2017,9,9)
# d.echo_date()
#
# d1 = Date.from_str('2018-10-19')
# d1.echo_date()
print "legal" if Date.is_date_legal('2017-13-16') else "illegal"