0

我有这样的课:

class MyClass(object):

    def f_1(self,x):
        return foo(x, self.property_1)

    def f_2(self,x):
        return foo(x, self.property_2)

这个想法是多个函数f_n具有共同的结构,但依赖于property_n类的不同属性。

我寻找一种更紧凑的方式来f_n定义__init__? 我想到了类似的东西

class MyClass(object):

    def __init__(self):
        self.f_1 = self.construct_function(self.property_1)
        self.f_2 = self.construct_function(self.property_2)

    def construct_function(self, property):
        # ???    

这就是我的想法,但我不知道如何定义它construct_function。'property' 是逐值类型是很重要的。

编辑:

我简化了Martijn对此解决方案的非常好的回答,效果很好:

def construct_function(property_name):
    def f_n(self, x):
        return foo(x, getattr(self, property_name))

    return f_n

class MyClass2(object):

    f_1 = construct_function('property_1')
    f_2 = construct_function('property_2')

只是想在这里提一下,因为不允许多行注释...

4

2 回答 2

1

如果要为每个类生成这些方法,请使用类装饰器:

def property_functions(**properties):
    def construct_method(prop):
        def f_n(self):
            return foo(getattr(self, prop))
        return f_n

    def class_decorator(cls):
        for name, prop in properties.iteritems():
            setattr(cls, name, construct_method(prop))

        return cls

    return class_decorator

然后像这样使用它:

@property_functions(f_1='property_1', f_2='property_2')
class MyClass(object):
    property_1 = 'foo'
    property_2 = 'bar'

示范:

>>> def foo(value): print value
... 
>>> @property_functions(f_1='property_1', f_2='property_2')
... class MyClass(object):
...     property_1 = 'foo'
...     property_2 = 'bar'
... 
>>> mc = MyClass()
>>> mc.f_1()
foo
>>> mc.f_2()
bar
于 2013-04-04T11:14:52.027 回答
0

您可以查看getattrgetattribute。它们允许您动态创建和引用属性。例如

它的工作原理是这样的:

class foo:
    def __init__(self):
        self.a = "a"
    def __getattr__(self, attribute):
        return "You asked for %s, but I'm giving you default" % attribute


>>> bar = foo()
>>> bar.a
'a'
>>> bar.b
"You asked for b, but I'm giving you default"
>>> getattr(bar, "a")
'a'
>>> getattr(bar, "b")
"You asked for b, but I'm giving you default"
于 2013-04-04T11:19:34.033 回答