我正在尝试创建一个阻止某些方法执行的包装器。经典的解决方案是使用这种模式:
class RestrictingWrapper(object):
def __init__(self, w, block):
self._w = w
self._block = block
def __getattr__(self, n):
if n in self._block:
raise AttributeError, n
return getattr(self._w, n)
这个解决方案的问题是每次调用都会引入开销,所以我尝试使用 MetaClass 来完成相同的任务。这是我的解决方案:
class RestrictingMetaWrapper(type):
def __new__(cls, name, bases, dic):
wrapped = dic['_w']
block = dic.get('_block', [])
new_class_dict = {}
new_class_dict.update(wrapped.__dict__)
for attr_to_block in block:
del new_class_dict[attr_to_block]
new_class_dict.update(dic)
return type.__new__(cls, name, bases, new_class_dict)
与简单的类完美配合:
class A(object):
def __init__(self, i):
self.i = i
def blocked(self):
return 'BAD: executed'
def no_blocked(self):
return 'OK: executed'
class B(object):
__metaclass__ = RestrictingMetaWrapper
_w = A
_block = ['blocked']
b= B('something')
b.no_blocked # 'OK: executed'
b.blocked # OK: AttributeError: 'B' object has no attribute 'blocked'
ndarray
问题来自numpy等“更复杂”的类:
class NArray(object):
__metaclass__ = RestrictingMetaWrapper
_w = np.ndarray
_block = ['max']
na = NArray() # OK
na.max() # OK: AttributeError: 'NArray' object has no attribute 'max'
na = NArray([3,3]) # TypeError: object.__new__() takes no parameters
na.min() # TypeError: descriptor 'min' for 'numpy.ndarray' objects doesn't apply to 'NArray' object
我假设我的元类定义不明确,因为其他类(例如:pandas.Series)会遇到奇怪的错误,比如没有阻止指定的方法。
你能找到错误在哪里吗?还有其他想法可以解决这个问题吗?
更新: nneonneo 的解决方案效果很好,但似乎包装类可以通过类定义中的一些黑魔法来打破阻塞器。
使用 nneonneo 的解决方案:
import pandas
@restrict_methods('max')
class Row(pandas.Series):
pass
r = Row([1,2,3])
r.max() # BAD: 3 AttributeError expected