如何在Python中实现ObjC类别?

2024-10-03 23:19:42 发布

您现在位置:Python中文网/ 问答频道 /正文

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())

Tags: 方法代码nameself程序声明getdef
3条回答

为什么不直接动态地添加方法呢?在

>>> class Foo(object):
>>>     pass
>>> def newmethod(instance):
>>>     print 'Called:', instance
...
>>> Foo.newmethod = newmethod
>>> f = Foo()
>>> f.newmethod()
Called: <__main__.Foo object at 0xb7c54e0c>

我知道Objective-C,这看起来就像分类。唯一的缺点是不能对内置或扩展类型执行此操作。在

我想出了一个类装饰器的实现。我使用的是python2.5,所以我还没有用decorator语法对它进行实际测试(这很好),而且我不确定它的功能是否正确。但看起来像这样:

在pycategories.py在

"""
This module implements Obj-C-style categories for classes for Python

Copyright 2009 Ulrik Sverdrup <ulrik.sverdrup@gmail.com>
License: Public domain
"""

def Category(toclass, clobber=False):
    """Return a class decorator that implements the decorated class'
    methods as a Category on the class @toclass

    if @clobber is not allowed, AttributeError will be raised when
    the decorated class already contains the same attribute.
    """
    def decorator(cls):
        skip = set(("__dict__", "__module__", "__weakref__", "__doc__"))
        for attr in cls.__dict__:
            if attr in toclass.__dict__:
                if attr in skip:
                    continue
                if not clobber:
                    raise AttributeError("Category cannot override %s" % attr)
            setattr(toclass, attr, cls.__dict__[attr])
        return cls
    return decorator

Python的setattr函数使这一点变得简单。在

# categories.py

class category(object):
    def __init__(self, mainModule, override = True):
        self.mainModule = mainModule
        self.override = override

    def __call__(self, function):
        if self.override or function.__name__ not in dir(self.mainModule):
            setattr(self.mainModule, function.__name__, function)

^{pr2}$

相关问题 更多 >