如果为true:destruct Class

时间:2014-06-01 19:28:37

标签: python oop python-2.7

我想知道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/");

2 个答案:

答案 0 :(得分:4)

是。这就是例外情况。

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__方法中引发了异常,因此从未完成赋值,因此实例没有引用并立即被删除。

答案 1 :(得分:3)

处理此问题的正确方法可能是引发异常。像

这样的东西
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/");