在 Python3 中动态装饰类中的函数 [英] Dynamically decorate a function inside a class in Python3

查看:66
本文介绍了在 Python3 中动态装饰类中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是动态/运行时方法的扩展在 Python 中创建(代码生成)

@John Montgommery 正确回答了@Eli Bendersky 的问题,即您可以使用此逻辑动态创建具有函数的类:

@John Montgommery properly answered @Eli Bendersky 's question that you can dynamically create a class with function using this logic:

class Dynamo(object):
    pass

def add_dynamo(cls,i):
    def innerdynamo(self):
        print "in dynamo %d" % i
    innerdynamo.__doc__ = "docstring for dynamo%d" % i
    innerdynamo.__name__ = "dynamo%d" % i
    setattr(cls,innerdynamo.__name__,innerdynamo)

for i in range(2):
    add_dynamo(Dynamo, i)

d=Dynamo()
d.dynamo0()
d.dynamo1()

我的问题是:如何使用需要参数的装饰器来装饰该类中的结果函数?

My question is: How do you decorate the resulting functions within that class with a decorator that needs a parameter?

例如:静态函数定义:

class MyTaskSequence(TaskSequence):
    @seq_task(1)
    def sequence1(self):
        self.client.get("/devops/")

    @seq_task(2)
    def sequence2(self):
        self.client.get("/blog/")

我尝试了什么:

class MyTaskSequence(TaskSequence):
    pass


def add_sequence(cls, order, path):
    def sequence(self):
        self.client.get(path)
    sequence.__name__ = "sequence%d" % order
    setattr(cls, sequence.__name__, seq_task(order)(sequence))

add_sequence(MyTaskSequence, 1, "/devops/")
add_sequence(MyTaskSequence, 2, "/blog/")

推荐答案

可以在创建方法时直接应用装饰器:

You can directly apply the decorator when creating the method:

def add_sequence(cls, order, path):
    @seq_task(order)
    def sequence(self):
        self.client.get(path)
    sequence.__name__ = "sequence%d" % order
    setattr(cls, sequence.__name__, sequence)

这篇关于在 Python3 中动态装饰类中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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