为每个问题Python生成一次随机值

时间:2015-04-15 14:25:43

标签: python random

我正在尝试为拍卖生成随机标题,然后在方法之外使用它。

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?我希望它在两种方法中是相同的,但对于每个寄售(测试用例)都是不同的

如何为每批货物生成一次?

3 个答案:

答案 0 :(得分:1)

那是因为_title_uuidclass 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)

    # ...

答案 1 :(得分:0)

我认为您应该在__init__方法中定义_title_uuid,因为每次都会更改类上的值。

在你的情况下,它可能是:

def __init__(self, *args, **kw):
   super(AddConsignmentPage, self).__init__(*args, **kw)
   self._title_uuid = get_random_uuid(7)

答案 2 :(得分:0)

我通过将ViewConsignmentsPage._title_uuid = self._title_uuid添加到init方法来修复此问题

add_consignment.py:

from pages.view_consignments import ViewConsignmentsPage

class AddConsignmentPage(BasePage):

    def __init__(self, driver):
        super(AddConsignmentPage, self).__init__(driver, self._title)
        self._title_uuid = get_random_uuid(7)
        ViewConsignmentsPage._title_uuid = self._title_uuid