动态语言的特性
1.给类添加方法
import types
#定义了一个类
class Person(object):
num = 0
def __init__(self, name = None, age = None):
self.name = name
self.age = age
def eat(self):
print("eat food")
#定义一个实例方法
def run(self, speed):
print("%s在移动, 速度是 %d km/h"%(self.name, speed))
#定义一个类方法
@classmethod
def testClass(cls):
cls.num = 100
#定义一个静态方法
@staticmethod
def testStatic():
print("---static method----")
#创建一个实例对象
P = Person("老王", 24)
#调用在class中的方法
P.eat()
#给这个对象添加实例方法
P.run = types.MethodType(run, P)
#调用实例方法
P.run(180)
#给Person类绑定类方法
Person.testClass = testClass
#调用类方法
print(Person.num)
Person.testClass()
print(Person.num)
#给Person类绑定静态方法
Person.testStatic = testStatic
#调用静态方法
Person.testStatic()
类装饰器
class Test(object):
def __init__(self, func):
print("---初始化---")
print("func name is %s"%func.__name__)
self.__func = func
def __call__(self):
print("---装饰器中的功能---")
self.__func()
#说明:
#1. 当用Test来装作装饰器对test函数进行装饰的时候,首先会创建Test的实例对象
# 并且会把test这个函数名当做参数传递到__init__方法中
# 即在__init__方法中的func变量指向了test函数体
#
#2. test函数相当于指向了用Test创建出来的实例对象
#
#3. 当在使用test()进行调用时,就相当于让这个对象(),因此会调用这个对象的__call__方法
#
#4. 为了能够在__call__方法中调用原来test指向的函数体,所以在__init__方法中就需要一个实例属性来保存这个函数体的引用
# 所以才有了self.__func = func这句代码,从而在调用__call__方法中能够调用到test之前的函数体
@Test
def test():
print("----test---")
test()#如果把这句话注释,重新运行程序,依然会看到"--初始化--"
元类
元类就是用来创建类的“东西”。你创建类就是为了创建类的实例对象,不是吗?但是我们已经学习到了Python中的类也是对象。
元类就是用来创建这些类(对象)的,元类就是类的类,你可以这样理解为:
MyClass = MetaClass() #使用元类创建出一个对象,这个对象称为“类”
MyObject = MyClass() #使用“类”来创建出实例对象
你已经看到了type可以让你像这样做:
MyClass = type('MyClass', (), {})
内建函数
1.range
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers
testList = [x+2 for x in range(5)]
In [22]: testList
Out[22]: [2, 3, 4, 5, 6]
2.map函数
#函数需要一个参数
map(lambda x: x*x, [1, 2, 3])
#结果为:[1, 4, 9]
#函数需要两个参数
map(lambda x, y: x+y, [1, 2, 3], [4, 5, 6])
#结果为:[5, 7, 9]
3.filter函数
filter函数会对序列参数sequence中的每个元素调用function函数,最后返回的结果包含调用结果为True的元素。
filter(lambda x: x%2, [1, 2, 3, 4])
[1, 3]
4.reduce函数
reduce(lambda x, y: x+y, [1,2,3,4])
10
reduce(lambda x, y: x+y, [1,2,3,4], 5)
15
reduce(lambda x, y: x+y, ['aa', 'bb', 'cc'], 'dd')
'ddaabbcc'
5.sorted函数
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
集合
集合与之前列表、元组类似,可以存储多个数据,但是这些数据是不重复的
集合对象还支持union(联合), intersection(交), difference(差)和sysmmetric_difference(对称差集)等数学运算.
>>> x = set('abcd')
>>> x
{'c', 'a', 'b', 'd'}
>>> type(x)
<class 'set'>
>>>
>>>
>>> y = set(['h','e','l','l','o'])
>>> y
{'h', 'e', 'o', 'l'}
>>>
>>>
>>> z = set('spam')
>>> z
{'s', 'a', 'm', 'p'}
>>>
>>>
>>> y&z #交集
set()
>>>
>>>
>>> x&z #交集
{'a'}
>>>
>>>
>>> x|y #并集
{'a', 'e', 'd', 'l', 'c', 'h', 'o', 'b'}
>>>
>>> x-y #差集
{'c', 'a', 'b', 'd'}
>>>
>>>
>>> x^z #对称差集(在x或z中,但不会同时出现在二者中)
{'m', 'd', 's', 'c', 'b', 'p'}
>>>
>>>
>>> len(x)
4
>>> len(y)
4
>>> len(z)
4
>>>