在初始化物件屬性以指向物件方法后,變數將不會被評估為與物件方法相同(使用“is”)。它仍將被評估為與該方法具有相等 (==)。
class SomeClass:
def __init__(self):
self.command = self.do_something
def do_stuff(self):
print('c1:', id(self.command))
print('c2:', id(self.do_something))
if self.command is self.do_something:
return 'Commands match (is)'
elif self.command == self.do_something:
return 'Commands match (==)'
return 'Commands do not match at all'
def do_something(self):
pass
some_object = SomeClass()
print(some_object.do_stuff())
print()
def some_func():
pass
command = some_func
print('c1:', id(some_func))
print('c2:', id(command))
if some_func is command:
print('Commands match (is)')
else:
'Commands do not match at all'
我期待 self.command 和 self.do_something 的 ID 相同,就像 some_func 和命令 ID 相同。
uj5u.com熱心網友回復:
每次通過實體訪問方法時,都會回傳一個method包含實體和底層函式的新實體。如果兩個method實體包裝相同的實體和相同的函式,則它們比較相等。(據我所知,這在任何地方都沒有記錄——實體方法物件的檔案中沒有提到它——但可以在CPython 源代碼中看到。)
因此,即使self.command(先前創建的系結方法) 和self.do_something是 的不同實體method,它們也都包裝了相同的實體 ( self)SomeClass和相同的函式 ( SomeClass.do_something)。
有關function值如何生成method實體的詳細資訊,請參閱描述符 HowTo 指南。
(實體方法物件記錄在語言檔案的第 3.2 節中。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532034.html
標籤:Python功能班级
上一篇:更正python代碼以使用函式
