python - 如果为真 : destruct Class

标签 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/");

最佳答案

是的。这就是异常的用途。

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

关于python - 如果为真 : destruct Class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23983614/

相关文章:

python - 我可以将 matplotlib 动画保存为 webm 格式吗?

oop - 如何在 Matlab 中访问父类(super class)的常量属性?

mysql - 安装 mysql python 时遇到问题,在 django 中找不到 mysqldb 模块

Python Dbus : How to export Interface property

python - 如何将 django call_command 的输出保存到变量或文件中

c++ - 在 C++ 中重载显式构造函数

python - 狮身人面像警告 : targets for x source files that are out of date

python - 如何在python中建立一个正规的表情符号词汇表?

python - 无法评估空值的列

Java 打印方法在类里面不起作用