简体   繁体   English

如果子类在python中覆盖父类的方法,如何引发错误?

[英]How to raise an error if child class override parent's method in python?

我正在做一个类,它将成为另一个类的基础,我想禁止在某些情况下覆盖某些方法,而我只是不知道该怎么做。

您正在寻找super() 函数

In python functions are just members of a class.在python中,函数只是类的成员。 You can replace them ( What is monkey patching ) to do somehting completely different.你可以替换它们( 什么是猴子补丁)来做一些完全不同的事情。

So even code that is NOT a subclass can substitute a classes function to do different things.因此,即使不是子类的代码也可以替代类函数来做不同的事情。

You can name-mangle functions - but that is also circumventable - and they also can be monkey-patched:您可以对函数进行命名 - 但这也是可以规避的 - 它们也可以被猴子修补:

class p:
  def __init__(self):
    pass

  def __secret(self):
    print("secret called")

  def __also_secret(self):
    print("also_secret called")

  def not_secret(self):
    def inner_method():
      print("inner called")
    inner_method()


class r(p):
  def __secret(self):  # override existing function
    print("overwritten")

Demo:演示:

a = p()
b = r()

# get all the respective names inside the class instance
c = [n for n in dir(a) if n.startswith("_p__")]
d = [n for n in dir(b) if n.startswith("_r__")]

# call the hidden ones and monkey patch then call again
for fn in c:
    q = getattr(a, fn)
    q() # original executed although "hidden"
    q = lambda: print("Monkey patched " + fn)
    q() # replaced executed

# call the hidden ones and monkey patch then call again
for fn in d:
    q = getattr(b, fn)
    # original executed although "hidden"
    q = lambda: print("Monkey patched " + fn)
    q() # replaced executed


# call public function
a.not_secret()
try:
    # a.inner_method() # does not work
    a.not_secret.inner_method() # does also not work as is it scoped inside
except AttributeError as e:
    print(e)


a.not_secret = lambda: print("Monkey patched")
a.not_secret()

Output:输出:

also_secret called                       # name mangled called
Monkey patched _p__also_secret           # patched of name mangled called
secret called                            # name mangled called
Monkey patched _p__secret                # patched of name mangled called
Monkey patched _r__secret                # overwritten by subclass one called
inner called                             # called the public that calls inner
'function' object has no attribute 'inner_method'  # cannot get inner directly
Monkey patched

If you want this feature you need to use a different language - not python.如果您想要此功能,您需要使用不同的语言 - 而不是 python。

One way of doing this is using "class decorator" to compare methods of the class itself and it's parent.一种方法是使用“类装饰器”来比较类本身及其父类的方法。 This can be done using __init_subclass__ as well.这也可以使用__init_subclass__来完成。 I will show you both:我将向你们展示:


Class decorator :类装饰器

from inspect import isfunction


def should_not_override_parents_method(cls):
    parents_methods = set(k for k, v in cls.__base__.__dict__.items() if isfunction(v))
    class_methods = set(k for k, v in cls.__dict__.items() if isfunction(v))
    diff = parents_methods & class_methods

    if diff:
        raise Exception(f"class {cls.__name__} should not implement parents method: "
                        f"'{', '.join(diff)}'")
    return cls


class A:
    def fn_1(self):
        print("A : inside fn_1")


@should_not_override_parents_method
class B(A):
    def fn_1(self):
        print("B : inside fn_1")

    def fn_2(self):
        print("B : inside fn_2")

output:输出:

Traceback (most recent call last):
  File "<>", line 21, in <module>
    class B(A):
  File "<>", line 10, in should_not_override_parents_method
    raise Exception(f"class {cls.__name__} should not implement parents method: "
Exception: class B should not implement parents method: 'fn_1'

__init_subclass__ : __init_subclass__

from inspect import isfunction


class A:
    def __init_subclass__(cls, **kwargs):
        parents_methods = set(k for k, v in cls.__base__.__dict__.items() if isfunction(v))
        class_methods = set(k for k, v in cls.__dict__.items() if isfunction(v))
        diff = parents_methods & class_methods

        if diff:
            raise Exception(f"class {cls.__name__} should not implement parents method: "
                            f"'{', '.join(diff)}'")

    def fn_1(self):
        print("A : inside fn_1")


class B(A):
    def fn_1(self):
        print("B : inside fn_1")

    def fn_2(self):
        print("B : inside fn_2")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM