簡體   English   中英

Python - 確定類方法是被覆蓋還是繼承

[英]Python - Determine if class method is overriden or inherited

如果可能的覆蓋在實現過程中沒有被標記為這樣,有沒有辦法檢查類方法是覆蓋還是從基類繼承?

class Super(object):
  def method(self, x, y):
    v = x + y
    return v

class Sub1(Super):
  def method(self, x, y):
    v = x + y + 10 # the calcs are irrelevant, not a reliable way to determine if inherited
    return v

class Sub2(Super):
  def ownMethod(self):
    return 'something'

Sub1.methodSub2.method方法或對它們的調用有什么區別可以區分它們是從Super繼承的嗎?

在實例級別

>>> getattr(Sub1().__class__, 'method')
<function __main__.Sub1.method(self, x, y)>

getattr(Sub2().__class__, 'method')
>>> <function __main__.Super.method(self, x, y)>

在班級

>>> getattr(Sub1, 'method')
<function __main__.Sub1.method(self, x, y)>

>>> getattr(Sub2, 'method')
<function __main__.Super.method(self, x, y)>

我發現Sub2.method是完全一樣的功能對象Super.method ,而Sub1.method是不同的對象:

>>> Sub2.method
<function Super.method at 0x7f9601345280>
>>> Super.method
<function Super.method at 0x7f9601345280>
>>> Sub2.method is Super.method
True
>>> Sub1.method is Super.method
False

所以如果你知道超類,你可以嘗試像這樣檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM