我想创建一个类,它不会Attribute Error对任何可能存在或不存在的方法进行调用:
我的课:
class magic_class:
...
# How to over-ride method calls
...
Run Code Online (Sandbox Code Playgroud)
预期产出:
ob = magic_class()
ob.unknown_method()
# Prints 'unknown_method' was called
ob.unknown_method2()
# Prints 'unknown_method2' was called
Run Code Online (Sandbox Code Playgroud)
现在,unknown_method并unknown_method2没有实际存在于类中,但是如何在python中拦截方法调用?
Sve*_*ach 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()
Run Code Online (Sandbox Code Playgroud)
版画
'unknown_method' was called
'unknown_method2' was called
Run Code Online (Sandbox Code Playgroud)
以防万一有人试图将未知方法委托给对象,代码如下:
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
Run Code Online (Sandbox Code Playgroud)
当您需要应用代理模式时,这非常有用。
此外,考虑到args 和 kwargs,您可以生成一个完全用户友好的界面,因为使用 MagicClass 的人将其视为真实的对象。