【问题标题】:How to make classes not run without being called?如何让类不被调用就不能运行?
【发布时间】:2020-08-29 13:50:25
【问题描述】:

如何防止一个类的执行而不把它放在主函数后面,我需要这个类来执行程序。我只想在声明后使用该类。

代码示例:

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

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

main()

输出:

this message should not have been displayed
hello world

【问题讨论】:

  • 原因和用例是什么?如果您不打印,则不会打印任何内容..
  • class 声明在 Python 中是可执行的,所以不,你不能——无论如何它不被认为是“调用它们”。无论如何,你为什么要在类体中调用print() 函数(而不是在类方法中)?
  • this message should not have been displayed - 你可以把它放在method,也许是__init__ 方法中。
  • 不要在你的类体内使用 print。在类方法中使用它
  • 你实际上想要 python来执行一些东西。否则装饰器将无法工作。

标签: python windows class printing message


【解决方案1】:

正如我们在Python Documentation 中看到的那样,“类定义是一个可执行语句”所以如果你直接写print("string"),你会在输出中看到字符串。

如果你想使用一个类来打印一个字符串,你必须在新的Class中创建一个方法,像这样:

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

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

main()

现在您的输出将是:

你好世界

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

h = Hello()
h.helloPrint()

【讨论】:

    【解决方案2】:

    好的,虽然"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
    

    这会将executionfoo 延迟到您选择的特定时间。

    【讨论】:

    • 哇,太完美了!
    【解决方案3】:

    你不能这样写……你必须把它放在构造函数的方法中 喜欢这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-05
      • 2017-09-29
      • 2018-09-19
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多