Home > Net >  Python. Apply getter to every attribute of a class
Python. Apply getter to every attribute of a class

Time:09-03

I have some class with attributes:

class Elements(Locators):
    tab_accept = (By.ID, 'droppableExample-tab-accept')
    box_acceptable = (By.ID, 'acceptable')

Which inherits from base class Locators:

class Locators:
    def __getattribute__(self, item):
        return WebElement(object.__getattribute__(self, item))

Initial idea was, that when I call an attribute within other classes, it would be returned with applied changes:

Elements.tab_accept -> WebElement(Elements.tab_accept)

But it returns it unchanged:

Elements.tab_accept -> Tuple[By, str]

How can I achieve a desired effect without writing every attribute with @property decorator?

CodePudding user response:

Instead of creating a new WebElement every time the attribute is accessed, would it make sense to give the attribute a WebElement value in __init_subclass__ instead?

Something like

class Locators:
    def __init_subclass(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        for k, v in cls.__dict__:
            setattr(cls, k, WebElement(v))

class Elements(Locators):
    tab_accept = (By.ID, 'droppableExample-tab-accept')
    box_acceptable = (By.ID, 'acceptable')

CodePudding user response:

Thanks to @rdas:

__getattribute__ works with objects. Try Elements().tab_accept

  • Related