Python:寻找一种为大量变量设置setter/getters的简便方法

jer*_*ean 4 python python-2.7 data-structures

我有一个类(Bar)嵌入在另一个类(Foo)中.

class Foo():
    class Bar():
        def __init__(self):
            self.a = 1
            self.b = 2
            ...
            self.z = 26


    def __init__(self):        
        self.bar = Bar()
Run Code Online (Sandbox Code Playgroud)

要访问类Bar的属性,用户需要执行以下操作:

>>> f = Foo()
>>> f.bar.a
1
Run Code Online (Sandbox Code Playgroud)

如何设置短点表示法以便用户可以同时使用:

>>> f.bar.a
1
Run Code Online (Sandbox Code Playgroud)

>>> f.a
1
Run Code Online (Sandbox Code Playgroud)

在我的例子中,我试图证明Bar类有很多变量.所以我不想手动为每个人编写一个getter/setter.所以我想在这样的for循环中使用property():

def __init__(self):
    self.bar = Bar()

    # Allow shorter dot notation
    for parm in self.bar.__dict__:
         setattr(self, i, getattr(bar, i))
         self.i = property(...)
Run Code Online (Sandbox Code Playgroud)

但我不确定如何在此上下文中使用属性而无需手动编写多个setter函数.

有关如何允许访问更短和更长记号的任何建议?

Mar*_*ers 16

这就是__getattr__钩子非常适合:

class Foo:
    # ...

    def __getattr__(self, name):
        return getattr(self.bar, name)
Run Code Online (Sandbox Code Playgroud)

__getattr__只调用缺少的属性; 因此,只Foo()传递实例上尚未存在的属性Foo().__getattr__().然后该getattr()函数允许您使用相同的属性名称self.bar; 如果该属性在那里也不存在,AttributeError则抛出一个,如预期的那样.

  • 在设置`self.bar`之前,请务必小心访问缺少的属性.在设置`self.bar`之前,甚至像[`if if hasattr(self,'bar')`](http://ideone.com/VQJWMu)之类的东西也会导致无限的`__getattr__`递归. (2认同)