0

I recently heared about properties, and that you can assign functions to the getter or setter of a attribute within a class. So you can do value Checks or different things.

I want to ask if it's possible to assign the same function to the getter of multiple attributes. To do that the function needs a dynamic return, so that the value X is returned if X was called, and Y if Y was called.

I could do a own getter for every Attribute, but in my case are 20+ Attributes which need to call that Function, so it would be nicer to have the dynamic call.

Testing with __getattributes__ was a total disaster, because I always got it looped endlessly, so either is wasn't possible that way or I just made mistakes.

Is that possible? Something like that:

class example():
    def __init__(self):
        self.__x = 1
        self.__y = 2

    def do_something(self):
        #Do something which is needed by multiple attributes
        #without changes
        attribute_name = '__' + attribute_name
        return self.__dict__[attribute_name]

    x = property(fget=do_something)
    y = property(fget=do_something)
    ...

EDIT 1:

My full Code where I could need dynamic property Getter. https://repl.it/@TobiasWagner/TV-DB-Django

Tkay
  • 103
  • 1
  • 14
  • Sure, you can implement the [descriptor protocol](https://docs.python.org/3/howto/descriptor.html) and just provide the backing attribute name, e.g. `x = magic_property('__x')`. Note that leading double underscores probably isn't what you want, though: https://stackoverflow.com/q/7456807/3001761. – jonrsharpe Nov 16 '18 at 11:53
  • You might also find https://codereview.stackexchange.com/q/98892/32391 interesting. – jonrsharpe Nov 16 '18 at 11:59
  • @jonrsharpe Thanks for the quick response, I kinda at a loss here. I don't quite understand whats going on at your post. I tried playing around with `__getattribute__(self, name)` but it failed because I can't use functions in there. And if I want to work with properties I need to transfer the name of the calling attribute to the new getter. Here is my Code, maybe it will help. [Class TBDB.py Row 180] [REPL.IT](https://repl.it/@TobiasWagner/TV-DB-Django) – Tkay Nov 16 '18 at 14:31
  • Please edit to give a [mcve] – jonrsharpe Nov 16 '18 at 14:36

0 Answers0