标签:style 进阶 自动 self attr dex 原来 根据 new
import functools
def index(a1,a2):
return a1 + a2
# 原来的调用方式
# ret = index(1,23)
# print(ret)
# 偏函数,帮助开发者自动传递参数
new_func = functools.partial(index,666)
ret = new_func(1)
print(ret)
2.执行父类方法
class Base(object):
def func(self):
print(‘Base.func‘)
class Foo(Base):
def func(self):
# 方式一:根据mro的顺序执行方法
# super(Foo,self).func()
# 方式二:主动执行Base类的方法
# Base.func(self)
print(‘Foo.func‘)
obj = Foo()
obj.func()
# print(Foo.__mro__)
3、面向对象的特殊方法
一
class Foo(object):
def __init__(self):
self.storage = {}
# object.__setattr__(self,‘storage‘,{})
def __setattr__(self, key, value):
print(key,value)
obj = Foo()
obj.xx = 123
结果
storage {}
xx 123
二
class Foo(object):
def __init__(self):
self.storage = {}
# object.__setattr__(self,‘storage‘,{})
def __setattr__(self, key, value):
print(key,value,self.storage) # 打印self.storage会报错,因为实例化对象先执行
#init,init中self.storage会触发seattr方法,seattr中的self.storge没有定义
obj = Foo()
obj.xx = 123
三
class Foo(object):
def __init__(self):
# self.storage = {}
object.__setattr__(self,‘storage‘,{})
def __setattr__(self, key, value):
print(key,value,self.storage)
obj = Foo()
obj.xx = 123
标签:style 进阶 自动 self attr dex 原来 根据 new
原文地址:https://www.cnblogs.com/weidaijie/p/10468643.html