2016-01-04 28 views
1

我有一類和構造,看起來像這樣:Python的詢問3個參數,當我經過2個2個參數,當我經過3

def init(log, edge): 
    if edge: 
     return Helper(log, edge) 
    return BookableProduct(log) 
class BookableProduct(): 
    # Add helper to property bag 
    def __init__(self, log, Kernel): 
     self.log = log 
     self.Kernel = Kernel 

我剛添加的內核參數,並將它casues錯誤。

如果我嘗試調用它像這樣:

import BookableProduct 
log = PyLogger.get(edge.Controller.Kernel) 
BookableProduct.init(log, edge) 

我得到的錯誤:

2016-01-04 15:12:33,422 [38] ERROR Panagora.WebCore.Scripting.DefaultRuntimeExtensionsManager - Unable to run script C:\dev\..\Extensions\Global.py 
Microsoft.Scripting.ArgumentTypeException: __init__() takes exactly 3 arguments (2 given) 

但是,如果我嘗試這樣運行:

import BookableProduct 
log = PyLogger.get(edge.Controller.Kernel) 
BookableProduct.init(log, edge, edge.Controller.Kernel) 

我得到以下錯誤:

2016-01-04 15:12:20,117 [36] ERROR Panagora.WebCore.Scripting.DefaultRuntimeExtensionsManager - Unable to run script C:\dev\git-sites\..\Extensions\Global.py 
Microsoft.Scripting.ArgumentTypeException: init() takes exactly 2 arguments (3 given) 
+7

那麼'init'定義在哪裏?你只顯示'__init__'。 *它們不是同一件事*。 'init'似乎調用'__init__',並且它不正確。 –

+0

'init'是'BookableProduct'模塊中定義的函數嗎?如果是這樣,該功能的來源是什麼? – vaultah

+0

已更新的問題。 – Himmators

回答

2

這並不完全清楚你想要做什麼,但我猜你想要一個產品工廠,在某些情況下返回BookableProduct的一個實例,在其他情況下返回一個Helper實例。

通過調用您的工廠函數(這不是任何類的方法)init,您在Python中具有特殊和保留的含義時會混淆問題。

相反,寫你的工廠是這樣的:

def product_factory(log, edge): 
    if edge: 
     return Helper(log, edge) 
    return BookableProduct(log, edge) 

請注意,我已經改變了名稱是什麼回事清晰,實例化BookableProduct(這些參數時添加第二個,此前失蹤的說法,以及self將傳遞給BookableProduct中的初始化程序__init__)。

1

__init__()是構造函數。你應該用類似於p = BookableProduct(log, edge)的東西構造你的對象,然後self將作爲第一個參數隱式傳遞給__init__(self, log, Kernel)

更新:您編輯的問題添加init()函數。在這兩個示例中,錯誤消息都很清晰準確。在第一個構造對象只傳遞一個參數時,當構造函數實際上需要3個參數時,其中一個是隱式傳遞的self,所以您應該傳遞兩個顯式參數。在第二個示例中,您使用錯誤的參數數量調用模塊範圍函數init()

0

self不是您應該作爲該方法的常規參數傳遞的參數。 Python爲你管理它,它總是你想調用方法的對象。

在不同的語言中,這個參數不存在,但是在Python中一切都應該是明確的,所以它只是強調在那裏你會在特定的方法上使用特定的方法。

例如:

class Foo: 
def bar(self, number): 
    self.number = number 
    print(self.number) 

您可以調用bar有:

Foo().bar(3) 

還有:

Foo.bar(Foo(), 3) 

而且這兩個例子只有打印3

相關問題