[英]How do python handles "self" attribute of a class internally, when the method is assigned to a variable
[英]How self variable works,when class is assigned to instance variables
我在機器人框架中遇到了以下代碼。 變量分配有不同的類名。 https://github.com/robotframework/robotframework/blob/master/src/robot/variables/variables.py
def __init__(self):
self.store = VariableStore(self)
self._replacer = VariableReplacer(self)
self._finder = VariableFinder(self.store)
為了理解以上分配的工作原理,我編寫了以下代碼,使用self時會拋出錯誤
class Foo(object):
def __init__(self):
pass
def addition(self):
return 5
class boo(object):
def __init__(self):
self.word = Foo(self)
def multiply(self):
return self.word.addition()
if __name__ == '__main__':
b = boo()
print(b.multiply()) #TypeError: __init__() takes 1 positional argument but 2 were given
在boo()類中使用以下組合時,獲取正確的輸出,即5。
問題是Foo
類中的def __init__(self)
。 您可以將參數self
用作參數,但是,與其他方法一樣,也不必專門傳遞該參數。因此,在boo
構造函數中,當您說self.word = Foo(self)
,實際上是在調用__init__
Foo
有兩個論點; 固有的self
和你所經過的boo
的self
。 這就解釋了為什么您得到__init__() takes 1 positional argument but 2 were given
的錯誤__init__() takes 1 positional argument but 2 were given
。
您對正在發生的事情的解釋有幾處錯誤。 首先,讓我們看一下代碼和您得到的錯誤:
b = boo()
print(b.multiply()) #TypeError: __init__() takes 1 positional argument but 2 were given
您的評論似乎暗示您認為調用b.multiply()
時發生錯誤。 但是,當您查看堆棧跟蹤時,您會發現它發生在執行b = boo()
:
Traceback (most recent call last):
File "/tmp/junk.py", line 16, in <module>
b = boo()
File "/tmp/junk.py", line 10, in __init__
self.word = Foo(self)
TypeError: __init__() takes 1 positional argument but 2 were given
請注意,堆棧跟蹤可以准確地告訴您問題所在。 您已將Foo.__init__
定義為采用單個參數,但給出了兩個。 為什么要給兩個? 在python中創建類的實例時,python會自動傳遞self
參數。 換句話說,如果執行b=boo()
,則函數將自動獲取self
而無需顯式傳遞它。這是python設計的非常基本的部分。 它與機器人框架無關。
在嘗試復制機器人代碼時,您創建了一個名為Foo
的類,該類帶有一個名為self
參數。 但是, VariableStore
對象具有兩個參數: self
和variables
:
class VariableStore(object):
def __init__(self, variables):
...
記住,python將自動傳遞self
,因此傳遞的第一個參數將與variables
parmeter關聯。
考慮以下代碼行:
self.store = VariableStore(self)
根據VariableStore
的定義方式,它與此完全相同:
self.store = VariableStore(variables=self)
注意self
與__init__
的self
參數不一樣。 它被傳遞給variables
參數。 這是因為python在構造類時會自動將self
作為第一個參數傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.