2015-04-15 60 views
1

我試圖爲拍賣生成隨機標題,然後在方法外部使用它。爲每個問題生成一次隨機值Python

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?我希望它在兩種方法中是相同的,但對於每一批貨都不同(測試用例)

如何爲每次寄售生成一次?

+0

可能的[Python中的靜態類變量]重複(http://stackoverflow.com/questions/68645/static-class-variables-in-python) – csl

回答

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

    # ... 
0

我想你應該定義一個__init__方法裏面_title_uuid因爲在類的價值將每一次改變。

你的情況可能是:

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