【问题标题】:How to, if possible, "unbound" bounded method?如果可能的话,如何“未绑定”有界方法?
【发布时间】:2021-06-10 13:03:47
【问题描述】:

我有一个无法修改的函数,因为它是第 3 方,假设它是 add 函数。

def add(a, b):
    print(a + b)

对于这个例子,让我们在 init 中调用它。它必须作为类变量分配给类。这样它将自动成为有界方法。为了防止“边界”,我需要用staticmethod 来装饰它。

class Base:
    func: Callable

    def __init__(self):
        self.func(a=1, b=2)


class Working(Base):
    func = staticmethod(add)

它工作正常,因为self 没有传递给函数。

我想知道是否可以“解绑”/使其在 init 中变为静态

class NotWorking(Base):
    func = add

    def __init__(self):
        staticmethod(self.func)(a=1, b=2)

它必须可以从 Base 类中重用,所以我不需要一遍又一遍地重写相同的东西。

class NotWorking2(Base):
    func = subtract

这不是我需要的东西,我只是想知道一旦它被绑定是否可以“解绑”它。

Working 类中,它只是一个函数

<function add at 0x7f1be89de1f0>

但在NotWorking 中,要么是

<bound method add of <__main__.NotWorking object at 0x7f0ed11e47f0>>

staticmethod 导致

TypeError: 'staticmethod' object is not callable

我见过'staticmethod' object is not callable,但它并没有真正回答我的问题。

我不认为这是可能的,但有没有更简洁的方法,所以如果我有很多这样的类,staticmethod 只能被调用一次?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    最简单的方法是干脆不把它作为self上的方法调用:

    class Base:
        func: typing.ClassVar[Callable]
    
        def __init__(self):
            type(self).func(a=1, b=2)
    
    class NowWorking(Base):
        func = add
    

    原答案:

    class NowWorking(Base):
        func = add
    
        def __init__(self):
            NowWorking.func(a=1, b=2)
    

    【讨论】:

    • 问题是我有很多这样的类,我的想法不是在init 中做任何事情,而是将其添加到接口/抽象类中 - 这里,Base
    • 你也可以打电话给type(self).func,我想这更灵活。
    • 对了,我觉得Base.func的类型应该是typing.ClassVar[Callable]
    • func = type(self).func 成功了。谢谢!你是对的类型。将在 3 分钟内接受。
    • 很高兴听到这个消息!我没有做出最初的回答,因为我认为有一个带有子类化的极端情况,但我尝试了一下,它工作得很好。
    猜你喜欢
    • 2022-12-10
    • 2012-05-03
    • 2016-08-27
    • 2010-09-08
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    相关资源
    最近更新 更多