考虑到以下情况,
项目列表类:
# 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
}
class ItemList(Item):
# --- these are data descriptors ---
# getting item_id value based on its item_num
item_id = TextReadOnly(locators['item_id'].format(item_num=self.item_num))
# getting item_title value based on its item_num
item_title = TextReadOnly(locators['item_title'].format(item_num=self.item_num))
def __init__(self, context, item_num=0):
# self.item_num can't be passed to locators
self.item_num = item_num
super(ItemList, self).__init__(
context
)
在这种情况下,我想将self.item_num
值传递给类中的item_num
内部定位器字典ItemList
。
原因是我想要每个item_id
并且item_title
指的是特定的item_num
.
我被困在这部分:
item_id = TextReadOnly(locators['item_id'].format(item_num=self.item_num))
item_title = TextReadOnly(locators['item_title'].format(item_num=self.item_num))
self.item_num
当实例已经创建时,值不能传递给定位器。
执行:
# filename: test.py
# print item_id values from item_num=1
item_1 = ItemList(context, 1)
print (‘Item_id_1: ’ + item_1.id)
# print item_id values from item_num=2
item_2 = ItemList(context, 2)
print (‘Item_id_2: ’ + item_2.id)
# ^ no result produced from item_1.id and item_2.id because self.item_num value can't be passed to locators
是否可以从实例变量更新数据描述符?
如何将实例变量值传递给数据描述符参数?
附加信息:
我试图调用item_id
和item_title
作为实例属性,但没有运气。我注意到数据描述符不能是这篇文章的实例属性:数据描述符应该是类属性
物品类别:
# filename: item.py
import abc
class Item(Page):
__metaclass__ = abc.ABCMeta
def __init__(self, context):
self.__context = context
super(Item, self).__init__(
self.__context.browser
)
描述符:
# filename: text_read_only.py
class TextReadOnly(object):
def __init__(self, locator):
self.__locator = locator
def __get__(self, instance, owner=None):
try:
e = instance.find_element_by_locator(self.__locator)
except AttributeError:
e = instance.browser.find_element_by_locator(self.__locator)
return e.text
def __set__(self, instance, value):
pass