Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: looking for a short-hand way to setup setters/getters for lots of variables

I have one class (Bar) embedded inside 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 class Bar, the user would need to the following:

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

How can I setup a short dot notation so that users can use BOTH:

>>> f.bar.a
1

and

>>> f.a
1

In my example, I'm trying to demonstrate that Bar class has a lot of variables. So I don't want to write a getter/setter for each one manually. So I was thinking to use the 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 unsure how to use property in this context without manually writing several setter functions.

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

like image 477
jersey bean Avatar asked Dec 03 '22 21:12

jersey bean


1 Answers

That's what the __getattr__hook is ideally suited for:

class Foo:
    # ...

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

__getattr__ is only called for attributes that are missing; so only attributes that are not already present on instances of Foo() are passed to Foo().__getattr__(). The getattr() function then lets you use the same attribute name on self.bar; if the attribute doesn't exist there either, an AttributeError is thrown, as would be expected.

like image 95
Martijn Pieters Avatar answered Dec 06 '22 10:12

Martijn Pieters