强制用户调用Object:__ call__

时间:2018-02-21 20:56:19

标签: python python-3.x

是否可以只允许用户在调用对象本身时调用任何/所有对象方法?

寻找有关如何执行此操作的不同示例

一些示例代码

class Test:
    def __init__(self, x=1):
        self.x = x
    def __call__(self, x=1):
        self.x = x
        return self
    def get(self, y):
        return (self.x * y)

t_obj = Test()

t_obj(2).get(1) # Acceptable case
t_obj.get(1) # Raises exception
t_obj().get(2) # Acceptable case

1 个答案:

答案 0 :(得分:0)

正确的方法

在我看来,你想要的是t_obj实际上是类,而不是Test的实例。然后它会给出您在示例中显示的确切行为。

class Test:
    def __init__(self, x=1):
        self.x = x

    def get(self, y):
        return (self.x * y)

t_obj = Test # not an object, actually a class

t_obj(2).get(1) # 2
t_obj.get(1) # Raises exception
t_obj().get(2) # 2

特别是,异常指出method get() must be called with Test instance,即你必须调用t_obj来实例化一个对象才能调用get(),这正是你想要的。

有趣的方式

虽然,假设你真的需要你的对象可以调用,这是一个让这个工作的hacky方法。它在被调用时替换了对象的get方法,替换了仅用于提升的占位符。

class Test:
    def __init__(self, x=1):
        self.x = x

    def __call__(self, x):
        self.x = x
        self.get = lambda y: self.x * y
        return self

    def get(self, y):
        raise AttributeError('call object first')

t_obj = Test()

t_obj.get(1) # Raises exception
t_obj(2)
t_obj.get(1) # 2