class myguidef handler(self)use self attr for state def makewidgets(self) button(text='spam'command=self handlerherethe event handler is self handler-- bound method object that remembers both self and mygui handler because self will refer to the original instance when handler is later invoked on eventsthe method will have access to instance attributes that can retain state between eventsas well as class-level methods with simple functionsstate normally must be retained in global variables or enclosing function scopes instead see also the discussion of __call__ operator overloading in for another way to make classes compatible with function-based apisand lambda in for another tool often used in callback roles as noted in the former of theseyou don' generally need to wrap bound method in lambdathe bound method in the preceding example already defers the call (note that there are no parentheses to trigger one)so adding lambda here would be pointlessclasses are objectsgeneric object factories sometimesclass-based designs require objects to be created in response to conditions that can' be predicted when program is written the factory design pattern allows such deferred approach due in large part to python' flexibilityfactories can take multiple formssome of which don' seem special at all because classes are also "first classobjectsit' easy to pass them around programstore them in data structuresand so on you can also pass classes to functions that generate arbitrary kinds of objectssuch functions are sometimes called factories in oop design circles factories can be major undertaking in strongly typed language such as +but are almost trivial to implement in python for examplethe call syntax we met in can call any class with any number of positional or keyword constructor arguments in one step to generate any sort of instance: def factory(aclass*pargs**kargs)return aclass(*pargs**kargsvarargs tupledict call aclass (or apply in onlyclass spam actuallythis syntax can invoke any callable objectincluding functionsclassesand methods hencethe factory function here can also run any callable objectnot just class (despite the argument namealsoas we learned in python has an alternative to aclass(*pargs**kargs)the apply(aclasspargskargsbuilt-in callwhich has been removed in python because of its redundancy and limitations designing with classes