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