2011-06-09 48 views
0

我對Python很陌生,在編寫應用程序時,最終導致了一個混亂的結構。下面的例子應該說明我正在嘗試做什麼。問題是我無法從common.py調用登錄方法,因爲它只在web.py或website2.py中定義。如何在模塊之間構造重複使用的代碼

模塊common.py

class Browser(): 

    def load_page(): 
     Login.login() 

模塊website1.py 進口common.py

class Login: 
    @staticmethod   
    def login(): 
     #code to login to this website 1 

模塊website2.py 進口common.py

@staticmethod 
class Login: 
    def login(): 
     #code to login to website 2 

任何思考如何重組這將不勝感激。

回答

1

首先,爲什麼要靜態方法?你可以在全球範圍內做def login

其次,您可以將類引用傳遞給Browser類。 (或如果你採取我的第一個建議,模塊參考)

class Browser(object): 
    def __init__(self, loginCls): 
     self.loginCls = loginCls 

    def login_page(self): 
     self.loginCls.login()