Python3 - 来自父类的调用方法

时间:2015-04-04 16:39:03

标签: python inheritance python-3.x

我需要从say_hello()课程运行MyException方法。有可能吗?

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

2 个答案:

答案 0 :(得分:1)

你可以继承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()没有自我参数,也许这就是你的意思),但这使得它不比函数调用更好:

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(), ...)

答案 1 :(得分:1)

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

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