Skip to main content
 首页 » 编程设计

Python 实例装饰器

2024年10月24日14lori

我想用来自“父”实例的装饰器装饰某些实例函数,有没有一种方法可以使用实例来装饰函数。

这是我需要做什么的想法;

class Foo(object): 
 
    def __init__(self): 
        pass 
 
    def set_configuration(self, function): 
        def config(*args, **kwargs): 
            # NOTE: this function needs to use instance variables. 
            print 'foo ' + function() 
        return config() 
 
class Bar(object): 
 
    def __init__(self, parent): 
        self.parent = parent 
 
    @self.parent.set_configuration 
    def set_config_2(self) 
        return 'bar' 
 
foo = Foo() 
foo.bar = Bar(foo) 
foo.bar.set_config_2 

编辑:

好的,伙计们,这是真正的问题,我有一个我需要与之交互的设备。所以一个设备可能有几个级别,即一个设备 有多个接口(interface),一个接口(interface)可能有多个 vlan。所以我的想法是,如果我想在一个接口(interface)上更改一个 vlan,而不是构建一个完整的命令,我想让父类处理它的命令级别的构建。所以我只想调用“更改 vlan”函数,它将它的命​​令的一部分发送到下一个级别以进行包装并向上发送链,直到它到达设备级别并将完整的命令发送到设备。

class Device(object): 
 
    def __init__(self): 
        self.interfaces = list() 
        self.ssh = ssh('blah') 
 
    def set_device(self, function): 
        self.ssh.command('setup commands') 
        self.ssh.command(wrapped command here) 
        self.ssh.command('exit commands') 
 
 
class Interface(object): 
 
    def __init__(self, name, parent): 
        self.name 
        self.parent 
        self.vlan = Vlan('name') 
 
    def set_interface(self): 
        return self.name 
 
 
class Vlan(object): 
 
    def __init__(self, name, parent): 
        self.name = name 
        self.parent = parent 
 
    def set_vlan(self): 
        return self.name  

我希望这更有意义。如果没有,请告诉我。

请您参考如下方法:

不,你不能在这里使用装饰器,因为在定义 Bar 时,parent 是未知的。

只需使用带有参数的set_configuration:

class Foo(object): 
 
    def __init__(self): 
        pass 
 
    def set_configuration(self, function): 
        def config(*args, **kwargs): 
            # NOTE: this function needs to use instance variables. 
            print 'foo ' + function() 
        return config 
 
class Bar(object): 
 
    def __init__(self, parent): 
        self.parent = parent 
 
    def set_config_2(self, args) 
        def inner_function(): 
            return 'bar' 
        return self.parent.set_configuration(inner_function)(args) 
 
 
foo = Foo() 
foo.bar = Bar(foo) 
foo.bar.set_config_2(123)