Problem with a dialog

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Dec 11 18:04:43 EST 2014


ast wrote:


> Since try() is a callback function called when a button is pushed,
> with the effect to open a dialog, I tried to define MyDialog class
> inside try(). The program is the following and it works. I no
> longer need to define test as global.
> Is it a good practice to define a class inside a function ?

Your question is too general. It *can* be good practice, or it can be bad
practice.

Classes are "first class values" (pun not intended) in Python, which means
you can pass them to functions and you can generate them on the fly and
return them from functions too. There is a downside to that: classes are
fairly hefty objects compared to instances, so if every time you call a
function you create an instance of a brand new class instead of re-using
the same class, your memory consumption will be much higher.

In your case, it probably doesn't matter: you only create a single MyDialog
instance, so it shouldn't matter that the class is created dynamically
inside the function. But I'm going to suggest a more object oriented
solution that avoids the local/global scoping issue completely:

* Make test an attribute of MyDialog (what some other languages 
  call "an instance variable").


from tkinter import *
import tkinter.simpledialog

class MyDialog(tkinter.simpledialog.Dialog):
    test = True
    def body(self, master):
        print(self.test)
    def apply(self):
        pass


def try_():
    setup = MyDialog(root)
 
root = Tk()
try_()



Technically, what I have done here is make "test" a class attribute, that
is, it will be shared by all MyDialog instances. But since there is only
one instance, that doesn't matter.

Another approach is to forgo the line "test = True" inside the class, and
set a per-instance attribute when the instance is created. Add this method
to the class:

    def __init__(self):
        self.test = True


Generally speaking, the __init__ method approach is more common.





-- 
Steven




More information about the Python-list mailing list