簡體   English   中英

Python:動態分配類方法

[英]Python: Dynamically assign class methods

本質上,這就是我要完成的工作:

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

我知道那是行不通的,它一直都在使用hasNoAttr。 我的第一個想法是使用裝飾器,但是我對裝飾器並不那么熟悉,因此我無法根據是否存在類屬性來弄清楚如何建立裝飾器。

實際問題部分:如何根據條件確定性地使函數為x函數或y函數。

您實際上無法使用__call__做這種事情-使用其他(非魔術)方法,您可以猴子補丁它們,但是使用__call__和其他魔術方法,您需要委派給magic方法中的適當方法本身:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM