如果为true:destruct类

2024-03-28 19:36:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道Python是否有办法避开__init__中的其他函数,直接转到__del__。例如

class API:

    Array = {"status" : False, "result" : "Unidentified API Error"}

    def __init__(self, URL):

        self.isBanned()
        print "This should be ignored."

    def isBanned(self):

        if True:
            goTo__del__()

    def __del__(self):
        print "Destructed"

API = API("http://google.com/");

Tags: 函数selfapifalseinitdefstatusresult
2条回答

是的。这就是例外。你知道吗

class BannedSite(Exception):
    pass

class API:

    Array = {"status" : False, "result" : "Unidentified API Error"}

    def __init__(self, URL):    
        if self.isBanned(URL):
            raise BannedSite("Site '%s' is banned" % URL)
        print "This should be ignored."

    def isBanned(self, URL):
        return True

异常是在__init__方法中引发的,因此永远不会完成赋值,因此实例没有引用,会立即被删除。你知道吗

正确的处理方法可能是引发异常。像这样的

class BannedException(Exception):
    """The client is banned from the API."""

class API:
    Array = {"status" : False, "result" : "Unidentified API Error"}

    def __init__(self, URL):

        self.isBanned()
        print "This should be ignored."

    def isBanned(self):

        if True:
            raise BannedException

API = API("http://google.com/");

相关问题 更多 >