Python3 - 从父 class 调用方法

Python3 - call method from parent class

我需要 运行 say_hello() 来自 MyException class 的方法。可能吗?

class MyClass:

    def say_hello():
        print('Hello!')

    class MyException(Exception):
        def __init__(self, *args, **kwargs):
            # say_hello()
            super().__init__(*args, **kwargs)

    try:
        do_something()
    except Exception:
        raise self.MyException("Something goes wrong, I'll just say hello")

您可以继承 MyClass,我认为这是您的意图(???):

class MyClass:
    def say_hello(self):
       print('Hello!')

class MyException(MyClass, Exception):
    def __init__(self, *args, **kwargs):
        self.say_hello()
        super(MyException, self).__init__(*args, **kwargs)

或者您可以将其设为静态方法(假设 say_hello() 没有 self 参数,也许这就是您的意思),但这并不比函数调用好:

class MyClass:
    @staticmethod
    def say_hello():
       print('Hello!')

class MyException(Exception):
    def __init__(self, *args, **kwargs):
        MyClass.say_hello()
        super(MyException, self).__init__(*args, **kwargs)

或者使用 MyClass 的实例

class MyClass:
    def say_hello(self):
       print('Hello!')

class MyException(Exception):
    def __init__(self, instance, *args, **kwargs):
        instance.say_hello()
        super(MyException, self).__init__(*args, **kwargs)

exc = MyException(MyClass(), ...)

没有。嵌套的 classes 在 Python 中并不特殊,并且无法访问包含的 class。因此,很少有理由使用它们。

我怀疑你来自 Java。你在这里根本不需要 MyClass;只需在模块级别同时定义 say_helloMyException