Python:动态分配类方法 [英] Python: Dynamically assign class methods

查看:83
本文介绍了Python:动态分配类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这基本上是我想要完成的:

  class Move(object):
def __init __ ,attr):
如果attr:
self.attr = Attr

如果hasattr(self,attr):
__call__ = self.hasTheAttr
else:
__call__ = self.hasNoAttr

def hasNoAttr(self):
#no args!

def hasTheAttr(func,arg1,arg2):
#do与args的事情

__call__ = hasNoAttr

我知道这不工作,它只是使用hasNoAttr所有的时间。我的第一个想法是使用装饰器,但我不是所有的熟悉他们,我不知道如何基于它是否一个类属性存在与否。



实际问题部分:我如何根据条件确定性地使函数x函数或y函数。

__ call __ - 与其他(非魔法)方法,你可以只是猴子补丁他们,但用 __调用__ 和其他魔法方法,你需要委托到魔法方法本身内的适当的方法:



class Move(object):
def __init __(self,Attr):
如果Attr:
self.attr = attr

如果hasattr(self,attr):
self._func = self.hasTheAttr
else:
self._func = self.hasNoAttr

def hasNoAttr(self):
#no args!

def hasTheAttr(func,arg1,arg2):
#do与args的事情

def __call __(self,* args):
return self._func(* args)


Essentially this is what I want to accomplish:

class Move(object):
    def __init__(self, Attr):
        if Attr:
            self.attr = Attr

        if hasattr(self, "attr"):
            __call__ = self.hasTheAttr
        else:
            __call__ = self.hasNoAttr

    def hasNoAttr(self):
        #no args!

    def hasTheAttr(func, arg1, arg2):
        #do things with the args

    __call__ = hasNoAttr

I know that that doesn't work, it just uses hasNoAttr all the time. My first thought was to use a decorator, but I'm not all that familiar with them and I couldn't figure out how to base it from whether or not a class attribute existed or not.

Actual question part: How would I be able to deterministically make a function either x function or y function depending on a condition.

解决方案

You can't really do this sort of thing with __call__ -- with other (non-magic) methods, you can just monkey-patch them, but with __call__ and other magic methods you need to delegate to the appropriate method within the magic method itself:

class Move(object):
    def __init__(self, Attr):
        if Attr:
            self.attr = Attr

        if hasattr(self, "attr"):
            self._func = self.hasTheAttr
        else:
            self._func = self.hasNoAttr

    def hasNoAttr(self):
        #no args!

    def hasTheAttr(func, arg1, arg2):
        #do things with the args

    def __call__(self,*args):
        return self._func(*args)

这篇关于Python:动态分配类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆