什么时候我可以省略自我 [英] When can I omit self

查看:238
本文介绍了什么时候我可以省略自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个简单的tkinter类的例子。
此示例适用于

I found this example of a simple tkinter class. The example works with either

'frame'或'self.frame'

'frame' or 'self.frame'

或者我会安全地省略self吗?

Why can or would I safely omit 'self'?

from Tkinter import *

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.button = Button(
            frame, text="QUIT", fg="red", command=frame.quit
            )
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text="Hello", command=self.say_hi)
        self.hi_there.pack(side=LEFT)

    def say_hi(self):
        print "hi there, everyone!"

root = Tk()

app = App(root)

root.mainloop()
root.destroy() # optional; see description below


推荐答案

frame 的局部变量,而不是像 self.frame 的对象属性。当您需要能够在创建对象的方法返回后引用对象时,您才应该使用对象属性。

In general, it's more efficient to use a local variable like frame rather than an object attribute like self.frame. You should only use an object attribute when you need to be able to refer to the object after the method that created it returns.

在Python中,存储在本地变量中的对象在函数或方法返回时会被垃圾回收,但这不是一个问题。 Frame对象本身将是持久的,因为它链接到您传递给 __ init __()的主对象。

In Python, objects that are stored in local variables get garbage-collected once the function or method returns, but that's not a problem here. The Frame object itself will be persistent because it's linked to the master object you pass to __init__().

这篇关于什么时候我可以省略自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆