简体   繁体   中英

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

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

您正在寻找super() 函数

In python functions are just members of a class. 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.

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. 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__ :

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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