简体   繁体   中英

Python. Apply getter to every attribute of a class

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?

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')

Thanks to @rdas:

__getattribute__ works with objects. Try Elements().tab_accept

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM