我正在尝试为拍卖生成随机标题,然后在方法之外使用它。
add_consignment.py:
class AddConsignmentPage(BasePage):
def __init__(self, driver):
super(AddConsignmentPage, self).__init__(driver, self._title)
self._title_uuid = get_random_uuid(7)
inst = AddConsignmentPage(AddConsignmentPage)
并且我想使用相同的 _title_uuid 来查看添加的托运(在搜索字段中输入其标题)
view_consignments.py
from pages.add_consignment import inst
class ViewConsignmentsPage(BasePage):
_title_uuid = inst._title_uuid
def check_added_consignment(self):
self.send_keys(self._title_uuid, self._auction_search)
在这种情况下,标题会生成两次,因此添加的托运中的标题与搜索字段中的标题不同
那么如何将 _title_uuid 的值从 AddConsignmentPage 传递到 ViewConsignmentsPage 呢?我希望两种方法相同,但每次托运(测试用例)不同
如何为每个托运生成一次?
最佳答案
那是因为 _title_uuid
是 class variable而不是实例变量:它只初始化一次。但如果你在构造函数中初始化它,它应该可以工作。
另请参阅Static class variables in Python
例如,
import random
class Foo:
num1 = random.randint(1,10)
def __init__(self):
self.num2 = random.randint(1,10)
for n in range(10):
foo = Foo()
print(foo.num1, foo.num2)
运行上面的命令会给出:
(7, 2)
(7, 6)
(7, 6)
(7, 5)
(7, 7)
(7, 1)
(7, 2)
(7, 3)
(7, 7)
(7, 7)
如果可以澄清任何事情,您也可以在这里执行 print(Foo.num1)
,但不能执行 print(Foo.num2)
因为它只存在于实例化对象中。
如您所见,num1
初始化一次,而 num2
为对象的每次实例化进行初始化。
在你的情况下,你可能可以这样做:
class AddConsignmentPage(BasePage):
def __init__(self):
super(AddConsignmentPage, self).__init__() # initializes BasePage
self._title_uuid = get_random_uuid(7)
# ...
关于python - 为每个问题生成一次随机值 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29652938/