Python:如何拦截一个不存在的方法调用?

时间:2012-06-04 10:26:30

标签: python

我想创建一个类,在调用任何可能存在或不存在的方法时都不会Attribute Error

我的班级:

class magic_class:
    ...
    # How to over-ride method calls
    ...

预期输出:

ob = magic_class()
ob.unknown_method()
# Prints 'unknown_method' was called

ob.unknown_method2()
# Prints 'unknown_method2' was called

现在,unknown_methodunknown_method2实际上并不存在于类中,但我们如何在python中拦截方法调用?

3 个答案:

答案 0 :(得分:27)

覆盖__getattr__()魔法:

class MagicClass(object):
    def __getattr__(self, name):
        def wrapper(*args, **kwargs):
            print "'%s' was called" % name
        return wrapper

ob = MagicClass()
ob.unknown_method()
ob.unknown_method2()

打印

'unknown_method' was called
'unknown_method2' was called

答案 1 :(得分:3)

以防万一有人试图将未知方法委托给对象,这是代码:

class MagicClass():
    def __init__(self, obj):
        self.an_obj = obj

    def __getattr__(self, method_name):
        def method(*args, **kwargs):
            print("Handling unknown method: '{}'".format(method_name))
            if kwargs:
                print("It had the following key word arguments: " + str(kwargs))
            if args:
                print("It had the following positional arguments: " + str(args))
            return getattr(self.an_obj, method_name)(*args, **kwargs)
        return method

当您需要应用Proxy pattern时,这非常有用。

而且,同时考虑了 args和kwargs ,允许您生成完全用户友好的界面,因为使用MagicClass的界面将其视为真实对象。

答案 2 :(得分:0)