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



为什么我可以这样做

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

而不是做

    instance = MyApp()
    instance.run()

我对 OOP 相当陌生,当我看到以第一个代码片段的方式编写的东西时,我感到相当困惑。这看起来如此普遍有什么原因吗?

两者之间有功能差异吗?

您在第一个代码块中基本上在执行与在第二个代码块中执行相同的操作。不同之处在于,在第一个中,您无法再次重用实例化的 MyApp() 类

但是,在第二个示例中,您定义了一个可以重用的对象。

编辑

正如@arekolek所说:

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

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

最新更新