Python: class实例化没有变量是什么意思

Python: What is the sense of class instantiation without variable

为什么我可以

class MyApp(App):
    def build(self):
        return Label(text="Hello World")

MyApp().run()

而不是做

    instance = MyApp()

    instance.run()

我对 OOP 还很陌生,当我看到以第一个代码片段的方式编写的内容时,我感到很困惑。为什么这看起来如此普遍?

两者在功能上有区别吗?

您基本上在第一个代码块和第二个代码块中做同样的事情。 不同之处在于,在第一个 中,您不能再次使用实例化的 MyApp() class

然而,在第二个示例中,您定义了一个可以重复使用的对象。

编辑

正如@arekolek 所说:

如果您使用 MyApp.run() 而不是将其分配给变量,Python 将在调用方法 Python 时立即释放对象占用的内存=33=]() 结束了。

p.s:我不是 python 的专业人士,可能是误会了...

不仅仅是不能重用实例化的MyApp()对象。

使用 MyApp.run() 而不是将其分配给变量可以让 Python 在 run() 调用完成后立即释放对象占用的内存。

在第二个例子中,如果你想释放内存,你需要手动del instance。一旦您离开定义了 instance 的块,内存也将被释放。例如:

def foo():
    instance = MyApp()
    instance.run()

foo()
# Memory freed automatically

instance = MyApp()
instance.run()
del instance

MyApp().run() # No need to clean-up