Pre: 类与函数的区别
类
一个对象的集合
定义了该集合中每个对象共有的属性和方法
对象是该类的一个实例
函数
可以重复使用的来实现某个功能的代码段
用来提高应用的模块性和代码的重复利用率
__call__函数
功能:如果一个对象提供了该方法,则我们可以像使用函数一样使用这个对象
class call_test():
def __init__(self,a):
print('run in init')
print('a: ',a)
def __call__(self,name):
print('run in call')
print('name: ‘,name)
call_test()是一个类,类初始化的时候,调用init函数,并且声称一个test对象实例。运行test对象就会去调用__call__函数(就相当于把这个对象当成函数来使用)
test=call_test(1)
"""
run in init
a: 1
"""
test(2)
"""
run in call
name: 2
__call__函数与类装饰器
class decorator():
def __init__(self,fun):
print ('run in init')
self.fun=fun
def __call(self,a,b)
self.fun(a,b)
@decorator
def add(a,b):
print('a+b',a+b)
add(1,2)
>>
run in init
a+b: 3
先设计一个装饰器类,然后在add函数时使用类装饰器,此时add函数变成了add=decorator(add),也就是把add函数的地址传入了decorator里的init函数,并且返回对象实例add,所以运行add时调用的是__call__()函数。
__new__函数和__init__函数
__init__方法是初始化方法,真正的构造方法是__new__(属于类方法)
pre: tuple元组是不可以改变的对象,自己构造的新的元组返回都是int.
class IntTuple(tuple):
def __init__(self,seq):
print('self:{},seq:{}'.format(self,seq))
super(IntTuple,self).__init__()
t=IntTuple((1,-1,'a'))
>>
self:(1,-1,'a'),seq(1.-1.'a')
(1,-1,'a')
可以看到传进去的是seq[1,-1,'a'],但是在__init__中是不能更改的
使用__new__进行更改
class IntTuple(tuple):
def __new__(cls, seq):
g=(x for x in seq if isinstance(x,int))
return super(IntTuple,cls).__new__(cls,g)
def __init__(self,seq):
print('self:",self)
super(InitTuple,self).__init__()
t=IntTuple([1,-1,'a'])
>>
self:(1,-1)
(1,-1)
__set__,__get__,__delete__
__set__: 在设计属性的时候被调用
__get__:在读取属性的时候被调用
__delete__:在删除属性的时候被调用