开发者

How can I tell what class in the polymorphic hierarchy contains the method I'm about to call?

开发者 https://www.devze.com 2023-04-06 20:51 出处:网络
If I have: class A(): def f(self): print(\"running function, f from class A\") class B(A)开发者_Python百科:

If I have:

class A():
    def f(self):
        print("running function, f from class A")
class B(A)开发者_Python百科:
    def __init__(self):
        A.__init__(self)
    def f(self):
        print("running function, f from class B")

and I make an instance of class B and call f on it, we all know we'll see the message about "from class B." But is there a way for me to inspect my object and make sure my sub-class has overridden my method? Something like:

obj = B()
assert(not obj.f.livesIn(A))


class A():
    def f(self):
        print("running function, f from class A")
class B(A):
    def f(self):
        print("running function, f from class B")
class C(A):
    pass

This shows that B.f does not equal A.f. So B must override f:

obj = B()
print(obj.__class__.f == A.f)
# False

This shows that C.f equals A.f. So C must not have overridden f:

obj = C()
print(obj.__class__.f == A.f)
# True


If you want to force the child class to override, you can raise NotImplementedError().

Doing the inspection is possible too... And I see unutbu just posted an example, so I won't repeat it. :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号