Python: looking for a short way to set setters / getters for many variables

I have one class (Bar) built into another class (Foo).

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


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

To access the attributes of the Bar class, the user will need the following:

>>> f = Foo()
>>> f.bar.a
1

How to set up short dot notation so users can use BOTH:

>>> f.bar.a
1

and

>>> f.a
1

In my example, I am trying to show that the Bar class has many variables. Therefore, I do not want to write a getter / setter for each of them manually. So I thought of using property () in a for loop like this:

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(...)

But I'm not sure how to use a property in this context without manually writing multiple setter functions.

Any suggestions on how to allow access to shorter and longer notations?

+4
1

, __getattr__ hook :

class Foo:
    # ...

    def __getattr__(self, name):
        return getattr(self.bar, name)

__getattr__ ; , Foo(), Foo().__getattr__(). getattr() self.bar; , AttributeError, .

+16

Source: https://habr.com/ru/post/1683553/


All Articles