看看這個使用繼承的簡單代碼:
class A:
def f(self):
pass
class B(A):
def __init__(self):
pass
b = B()
print(dir(b))
正如預期的那樣,此串列包含方法f,輸出為
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'f']
但是現在,請查看以下代碼:
class A:
def f(self):
pass
class B(A):
def __init__(self):
global s
s = super()
b = B()
print(dir(s))
print(s.f)
輸出是
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__self_class__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__thisclass__']
其中不包括功能f。
但是,在運行該行之后print(s.f),輸出是<bound method A.f of <__main__.B object at 0x00000*******>>
所以我的問題是,為什么s.f不是 AttributeError,即使dir(s)沒有說它有一個f屬性/方法?
我在 python3.9.7 上使用 IPython7.19.0
uj5u.com熱心網友回復:
根據檔案, Python dir()
如果物件未提供dir (),則該函式會盡力從物件的dict屬性(如果已定義)及其型別物件中收集資訊。結果串列不一定完整,當物件具有自定義getattr ()時可能不準確。
此外,根據檔案Python super()
回傳一個代理物件,該物件將方法呼叫委托給型別的父類或兄弟類。這對于訪問在類中被覆寫的繼承方法很有用。
object-or-type 確定要搜索的方法決議順序。搜索從型別之后的類開始。
因此,s.f委托給<bound method A.f of <__main__.B object at 0x00000*******>>
這里是一個很好的解釋super(),https://rhettinger.wordpress.com/2011/05/26/super-thinked-super/
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350742.html
上一篇:呼叫后Python設定類變數
