如何装饰一堂课? [英] How to decorate a class?

查看:70
本文介绍了如何装饰一堂课?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2.5中,有没有办法创建装饰类的装饰器?具体来说,我想使用装饰器将一个成员添加到类中,并更改构造函数以对该成员取一个值。

In Python 2.5, is there a way to create a decorator that decorates a class? Specifically, I want to use a decorator to add a member to a class and change the constructor to take a value for that member.

寻找类似以下内容(在'class Foo:'上有语法错误:

Looking for something like the following (which has a syntax error on 'class Foo:':

def getId(self): return self.__id

class addID(original_class):
    def __init__(self, id, *args, **kws):
        self.__id = id
        self.getId = getId
        original_class.__init__(self, *args, **kws)

@addID
class Foo:
    def __init__(self, value1):
        self.value1 = value1

if __name__ == '__main__':
    foo1 = Foo(5,1)
    print foo1.value1, foo1.getId()
    foo2 = Foo(15,2)
    print foo2.value1, foo2.getId()

我猜我真正想要的是一种在Python中执行类似C#接口的方法。我需要切换我的范例。

I guess what I'm really after is a way to do something like a C# interface in Python. I need to switch my paradigm I suppose.

推荐答案

我会第二个想法您可能希望考虑使用子类而不是您概述的方法。但是,不知道您的具体情况,YMMV:-)

I would second the notion that you may wish to consider a subclass instead of the approach you've outlined. However, not knowing your specific scenario, YMMV :-)

您正在考虑的是元类。元类中的 __ new __ 函数将传递该类的完整建议定义,然后可以在创建类之前重写该定义。那时,您可以将构造函数替换为新的构造函数。

What you're thinking of is a metaclass. The __new__ function in a metaclass is passed the full proposed definition of the class, which it can then rewrite before the class is created. You can, at that time, sub out the constructor for a new one.

示例:

def substitute_init(self, id, *args, **kwargs):
    pass

class FooMeta(type):

    def __new__(cls, name, bases, attrs):
        attrs['__init__'] = substitute_init
        return super(FooMeta, cls).__new__(cls, name, bases, attrs)

class Foo(object):

    __metaclass__ = FooMeta

    def __init__(self, value1):
        pass

替换构造函数可能会有些戏剧性,但是语言确实为这种深入的内省和动态修改提供了支持。

Replacing the constructor is perhaps a bit dramatic, but the language does provide support for this kind of deep introspection and dynamic modification.

这篇关于如何装饰一堂课?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆