日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python替代技术,Python超级方法和调用替代品

發(fā)布時(shí)間:2024/8/5 python 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python替代技术,Python超级方法和调用替代品 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

I see everywhere examples that super-class methods should be called by:

super(SuperClass, instance).method(args)

Is there any disadvantage to doing:

SuperClass.method(instance, args)

解決方案

Consider the following situation:

class A(object):

def __init__(self):

print('Running A.__init__')

super(A,self).__init__()

class B(A):

def __init__(self):

print('Running B.__init__')

# super(B,self).__init__()

A.__init__(self)

class C(A):

def __init__(self):

print('Running C.__init__')

super(C,self).__init__()

class D(B,C):

def __init__(self):

print('Running D.__init__')

super(D,self).__init__()

foo=D()

So the classes form a so-called inheritance diamond:

A

/ \

B C

\ /

D

Running the code yields

Running D.__init__

Running B.__init__

Running A.__init__

That's bad because C's __init__ is skipped. The reason for that is because B's __init__ calls A's __init__ directly.

The purpose of super is to resolve inheritance diamonds. If you un-comment

# super(B,self).__init__()

and comment-out

A.__init__(self)

the code yields the more desireable result:

Running D.__init__

Running B.__init__

Running C.__init__

Running A.__init__

Now all the __init__ methods get called. Notice that at the time you define B.__init__ you might think that super(B,self).__init__() is the same as calling A.__init__(self), but you'd be wrong. In the above situation, super(B,self).__init__() actually calls C.__init__(self).

Holy smokes, B knows nothing about C, and yet super(B,self) knows to call C's __init__? The reason is because self.__class__.mro() contains C. In other words, self (or in the above, foo) knows about C.

So be careful -- the two are not fungible. They can yield vastly different results.

Using super has pitfalls. It takes a considerable level of coordination between all the classes in the inheritance diagram. (They must, for example, either have the same call signature for __init__, since any particular __init__ would not know which other __init__ super might call next, or

else use **kwargs.) Furthermore, you must be consistent about using super everywhere. Skip it once (as in the above example) and you defeat the entire purpose of super.

See the link for more pitfalls.

If you have full control over your class hierarchy, or you avoid inheritance diamonds, then there is no need for super.

總結(jié)

以上是生活随笔為你收集整理的python替代技术,Python超级方法和调用替代品的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。