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

鸭子类型和类方法(或者,如何同时使用类和实例中的方法?)

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

鸭子类型和类方法(或者,如何同时使用类和实例中的方法?)

考虑

classinstancemethod
从formenpre重用装饰器。

https://bitbucket.org/formenpre/official-
formenpre/src/06d52c5b33c9/formenpre/declarative.py

class classinstancemethod(object):    """    Acts like a class method when called from a class, like an    instance method when called by an instance.  The method should    take two arguments, 'self' and 'cls'; one of these will be None    depending on how the method was called.    """    def __init__(self, func):        self.func = func    def __get__(self, obj, type=None):        return _methodwrapper(self.func, obj=obj, type=type)class _methodwrapper(object):    def __init__(self, func, obj, type):        self.func = func        self.obj = obj        self.type = type    def __call__(self, *args, **kw):        assert 'self' not in kw and 'cls' not in kw, ( "You cannot use 'self' or 'cls' arguments to a " "classinstancemethod")        return self.func(*((self.obj, self.type) + args), **kw)    def __repr__(self):        if self.obj is None: return ('<bound class method %s.%s>'         % (self.type.__name__, self.func.func_name))        else: return ('<bound method %s.%s of %r>'         % (self.type.__name__, self.func.func_name, self.obj))


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

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

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