Obj-C(我很久没有使用它)有一个叫做categories的东西来扩展类。用新方法声明一个类别并将其编译到程序中,类的所有实例都会突然拥有新方法。在
Python有mixin的可能性,我使用它,但是mixin必须从程序的底部使用:类必须自己声明它。在
预见的类别用例:假设你有一个大的类层次结构,它描述了与数据交互的不同方式,声明了获取不同属性的多态方法。现在,一个类别可以通过实现一个方便的接口在一个地方访问这些方法来帮助这些描述类的使用者。(例如,category方法可以尝试两种不同的方法并返回第一个定义的(非None)返回值。)
有没有办法用Python做到这一点?在
我希望这能澄清我的意思。关键是类别就像一个聚合接口,AppObj的使用者可以在其其代码中更改。在
class AppObj (object):
"""This is the top of a big hierarchy of subclasses that describe different data"""
def get_resource_name(self):
pass
def get_resource_location(self):
pass
# dreaming up class decorator syntax
@category(AppObj)
class AppObjCategory (object):
"""this is a category on AppObj, not a subclass"""
def get_resource(self):
name = self.get_resource_name()
if name:
return library.load_resource_name(name)
else:
return library.load_resource(self.get_resource_location())
为什么不直接动态地添加方法呢?在
我知道Objective-C,这看起来就像分类。唯一的缺点是不能对内置或扩展类型执行此操作。在
我想出了一个类装饰器的实现。我使用的是python2.5,所以我还没有用decorator语法对它进行实际测试(这很好),而且我不确定它的功能是否正确。但看起来像这样:
在pycategories.py在
Python的
setattr
函数使这一点变得简单。在在
^{pr2}$相关问题 更多 >
编程相关推荐