首页 > 编程语言 > 详细

python,decorator,class

时间:2014-02-07 18:05:20      阅读:344      评论:0      收藏:0      [点我收藏+]

http://stackoverflow.com/questions/9906144/python-decorate-a-class-by-defining-the-decorator-as-a-class

Apart from the question whether class decorators are the right solution to your problem:

in Python 2.6 and higher, there are class decorators with the @-syntax, so you can write:

@addIDclassFoo:pass

in older versions, you can do it another way:

classFoo:passFoo= addID(Foo)

Note however that this works the same as for function decorators, and that the decorator should return the new (or modified original) class, which is not what you‘re doing in the example. The addID decorator would look like this:

def addID(original_class):
    orig_init = original_class.__init__
    # make copy of original __init__, so we can call it without recursiondef __init__(self, id,*args,**kws):
        self.__id = id
        self.getId = getId
        orig_init(self,*args,**kws)# call the original __init__

    original_class.__init__ = __init__ # set the class‘ __init__ to the new onereturn original_class

You could then use the appropriate syntax for your python version as described above.

But I agree with others that inheritance is better suited if you want to override __init__.

python,decorator,class

原文:http://www.cnblogs.com/threef/p/3539479.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!