栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

class方法上的functools.partial

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

class方法上的functools.partial

您正在 函数 上创建局部 函数
,而不是方法上。

functools.partial()
对象不是描述符,它们本身不会添加
self
参数,也不能自己充当方法。您 只能
包装绑定的方法或函数,它们对于未绑定的方法根本不起作用。这是记录:

partial
对象就像
function
对象一样,它们是可调用的,弱引用的,并且可以具有属性。有一些重要的区别。例如,
__name__
__doc__
属性不会自动创建。同样,
partial
在类中定义的对象的行为类似于静态方法,并且在实例属性查找期间不会转换为绑定方法。

使用

property
s代替;这些 描述符:

class RGB(object):    def __init__(self, red, blue, green):        super(RGB, self).__init__()        self._red = red        self._blue = blue        self._green = green    def _color(self, type):        return getattr(self, type)    @property    def red(self): return self._color('_red')    @property    def blue(self): return self._color('_blue')    @property    def green(self): return self._color('_green')

从Python
3.4开始,您可以在此处使用新

functools.partialmethod()
对象。绑定到实例时,它将做正确的事情:

class RGB(object):    def __init__(self, red, blue, green):        super(RGB, self).__init__()        self._red = red        self._blue = blue        self._green = green    def _color(self, type):        return getattr(self, type)    red = functools.partialmethod(_color, type='_red')    blue = functools.partialmethod(_color, type='_blue')    green = functools.partialmethod(_color, type='_green')

但是这些

property
对象必须被调用,而对象可以用作简单属性。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639457.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号