如何使类不被调用就不运行?

问题描述

如何在不将其置于主函数后面的情况下防止其执行,我需要该类来执行程序。我只想在声明该类后使用它。

代码示例:

onSaveInstanceState(Bundle bundle)

输出

class Hello:
    print('this message should not have been displayed')

def main():
    print('hello world')

main()

解决方法

我们可以在Python Documentation中看到,“类定义是可执行语句” ,因此,如果直接编写print("string"),则会在输出中看到字符串

如果要使用类来打印字符串,则必须在新的类中创建一个方法,如下所示:

class Hello:
    def helloPrint():
        print('this message should not have been displayed')

def main():
    print('hello world')

main()

现在您的输出将是:

你好世界

您可以通过在前面的代码末尾写以下行来打印 Hello 类消息:

h = Hello()
h.helloPrint()
,

您不能这样写...您必须将其放在构造函数的方法中 像这样

class Hello():
    def __init__(self):
        print('this message should not have been displayed')


def main():
    print('hello world')


main()
hello = Hello()
,

好吧,因此在"a class definition is an executable statement"时,并非所有class语句都需要直接位于模块内部。还有这种模式:

def create():
    class foo:
        a = 1
        print('Inside foo')
    return foo

print('running')

C = create()

输出:

running
Inside foo

这会将execution中的foo延迟到您选择的特定时间。