Skip to content Skip to sidebar Skip to footer

Python - How To Pass Instance Variable Value To Descriptor Parameter?

Considering below case, ItemList Class: # filename: item_list.py # locators dictionary is intentionally placed outside `ItemList` class locators = { 'item_id': 'css=tr:nth-of-

Solution 1:

I found this article and came up with solution to add the descriptors to an object.

This solution below worked for me:

  1. Add __getattribute__ and __setattr__ into Item Class

    # filename: item.pyimport abc
    
    
    classItem(Page):
        __metaclass__ = abc.ABCMeta
    
        def__init__(self, context):
            self.__context = context
            super(Item, self).__init__(
                self.__context.browser
            )
    
        def__getattribute__(self, name):
            value = object.__getattribute__(self, name)
            ifhasattr(value, '__get__'):
                value = value.__get__(self, self.__class__)
            return value
    
        def__setattr__(self, name, value):
            try:
                obj = object.__getattribute__(self, name)
            except AttributeError:
                passelse:
                ifhasattr(obj, '__set__'):
                    return obj.__set__(self, value)
            returnobject.__setattr__(self, name, value)
    
  2. Move class attribute to instance attribute in ItemList constructor

    # filename: item_list.py# locators dictionary is intentionally placed outside `ItemList` class
    locators = {
        'item_id': 'css=tr:nth-of-type({item_num}) .id',
        'item_title': 'css=tr:nth-of-type({item_num}) .alert-rules',
        # other properties
    }
    
    
    classItemList(Item):
        def__init__(self, context, item_num=0):
            self.item_num = item_num
            # self.item_num is able to be passed to locators
            self.item_id = TextReadOnly(locators['item_id'].format(item_num=self.item_num))
            self.item_title = TextReadOnly(locators['item_title'].format(item_num=self.item_num))
    
            super(ItemList, self).__init__(
                context
            )
    

Post a Comment for "Python - How To Pass Instance Variable Value To Descriptor Parameter?"