Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python对内部类使用别名_Python - Fatal编程技术网

Python对内部类使用别名

Python对内部类使用别名,python,Python,我有以下代码示例 class Outer: class InnerException(Exception): pass def raise_inner(self): raise Outer.InnerException() def call_raise(self): try: self.raise_inner() except Outer.InnerException as e:

我有以下代码示例

class Outer:
    class InnerException(Exception): pass
    def raise_inner(self):
        raise Outer.InnerException()
    def call_raise(self):
        try:
            self.raise_inner()
        except Outer.InnerException as e:
            print "Handle me"

 Outer().call_raise()
我想做的是,不要在外部类中使用
Outer.InnerException
只需在外部类中使用
InnerException
,简而言之就是这样

class Outer:
    class InnerException(Exception): pass

    #InnerException = Outer.InnerException .. something like this, create some alias

    def raise_inner(self):
        raise InnerException()
    def call_raise(self):
        try:
            self.raise_inner()
        except InnerException as e:
            print "Handle me"

 Outer().call_raise()

调用方法时会查找名称
InnerException
,因此异常名称是非本地值。你可以写

class Outer:
    class InnerException(Exception): pass

    # methods

InnerException = Outer.InnerException
但这基本上违背了首先在类
Outer
内部定义
InnerException
的目的。你可以很容易地写

class Outer:
    # methods

class InnerException(Exception): pass

因为两者都使名称
InnerException
引用模块范围内的异常(尽管在第二种情况下,
InnerException
当然不再是
Outer
的类属性)。

您不能只引用类范围内声明的名称(除非您也在类范围内这样做)

或者:

class Outer:
    class InnerException(Exception): pass
    def raise_inner(self):
        raise self.InnerException()


我想您可以这样做,在每个函数的封闭范围内定义它,这将创建一个局部变量作为它的别名:

class Outer:
    class InnerException(Exception): pass
    def raise_inner(self, InnerException=InnerException):
        raise InnerException()
    def call_raise(self, InnerException=InnerException):
        try:
            self.raise_inner()
        except InnerException as e:
            print "Handle me"

Outer().call_raise()

Python中常用的方法是:将异常类放在模块范围内。请参阅关于Python的答案。
class Outer:
    class InnerException(Exception): pass
    def raise_inner(self, InnerException=InnerException):
        raise InnerException()
    def call_raise(self, InnerException=InnerException):
        try:
            self.raise_inner()
        except InnerException as e:
            print "Handle me"

Outer().call_raise()