python,decorator,class

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__.

转载于:https://www.cnblogs.com/threef/p/3539479.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值