15

我想创建一个不提供Attribute Error任何可能存在或不存在的方法的 on call 类:

我的课:

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_method并且unknown_method2实际上并不存在于类中,但是我们如何拦截 python 中的方法调用?

4

3 回答 3

34

覆盖__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
于 2012-06-04T10:31:23.157 回答
7

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

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

当您需要应用代理模式时,这非常有用。

此外,考虑到args 和 kwargs,允许您生成一个完全用户友好的界面,因为使用 MagicClass 的界面将其视为真实对象。

于 2020-06-10T12:47:24.160 回答
1

覆盖__getattr__;见http://docs.python.org/reference/datamodel.html

于 2012-06-04T10:29:37.830 回答