Re: [Tutor] Help understanding classes
On Fri, Nov 14, 2014 at 4:29 PM, Bo wrote: > Hello everyone, hope all is well. Was just wondering if I could get some > help understanding classes and how they work. What is the point in OOP if I > don’t understand classes, are classes not the heart and soul of OOP? I have > been trying to learn classes by practicing with Tkinter building GUIs. Below > is my code, which does work. It simply opens a window. I just don’t > understand why it works? GUI programming is a special class of programming. What makes it significantly different from what you might be used to is this: you eventually pass control of your program to some third-party manager. From that point forward, you don't do anything on your own. The third-party manager calls your functions when it decides that something interesting has happened that needs your input. This takes a large mental re-adjustment, from being the head, the one in charge of control flow, to being a servant, a provider of a service! Note that I haven't said anything about OOP, because fundamentally I think GUIs are different not because they're composed of classes, but because control flow is driven by something else. For Tkinter, the third-party manager is an "event loop" which we treat as a black box. We enter this event loop right here in your main function: # def main(): root = Tk() # ... code cut root.mainloop() ## Once we reach root.mainloop(), it's the event loop that dictates what happens next. We take our hands off the steering wheel. To follow along these lines, let's take a look at a simple button example here: http://effbot.org/tkinterbook/button.htm Here's the code: # import Tkinter master = Tkinter.Tk() def callback(): print "click!" b = Tkinter.Button(master, text="OK", command=callback) b.pack() Tkinter.mainloop() # Here, we tell the GUI system: when you press this button, call our "callback" function. We run the mainloop(). A window appears with a button, and when we press the button, we see that our function gets called. This is strange for beginners, because we're telling the GUI system how to use our functions. But we're not the ones calling them. Also, somehow we're using functions "in the future", rather than immediately by calling them. That's the big point of a line like: b = Tkinter.Button(master, text="OK", command=callback) where "callback" is a function. Note the lack of parens there! It's not being called yet. Instead, the function is just a value that the button knows about. The event loop will call that function later on. That's why we're saying "callback" instead of "callback()" on that line. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help understanding classes
On 15/11/14 00:29, Bo wrote: help understanding classes and how they work. What is the point in OOP if I don’t understand classes, are classes not the heart and soul of OOP? Actually not necessarily. There are OOP languages where classes are not included or little used. Javascript is a good example but there are others too. However, since this is a Python list, we'll ignore those and agree with you that you need to know about classes... :-) I have been trying to learn classes by practicing with Tkinter building GUIs. While OOP is usually used in creating GUIs they are not the best place to learn about classes because the GUI frameworks (Tkinter in your case) do a fair bit of magic internally that confuses things a little bit. window. I just don’t understand why it works? Let's start with that. Where would the rest of my code go That's where the GUI magic happens so the code doesn't go where you might initially think it would! Later... class test(Frame): This creates a new class called 'test' that defines a new kind of Frame object (style note: class names are usually capitalized so it should be called Test). This means that you can create instances of it (objects of type Test) using the usual Python syntax of class name followed by () so: myTestObject = Test() As a subclass of Frame it inherits a lot of functionality from the Frame class, including how to display itself on screen, resize itself and so on. A Frame is a general purpose GUI container (a bit like a visual list if you like, except it can only hold GUI widgets). As such it acts as the top level window of your application. All other widgets and sub-frames will go into the top level Frame. This is an important point. In a GUI there is a top level parent object and all other objects are children of that, They form a tree-like data structure called the containment tree. This tree is crucial to how GUIs interact with user events (and how the widgets communicate internally) and is the core of the GUI magic that I mentioned earlier. > def __init__(self, parent): > Frame.__init__(self, parent) > self.parent = parent > self.initUI() This is the first method of the class. A method is a special type of function that is defined inside a class and provides the functionality (or operations) of the class. In this case it is a special method that gets called by python when a new object of type Test is created (this is OOP magic not GUI magic, it happens for all classes). Its purpose is to initialize the data variables (or attributes) of the new instance. In your case that includes calling the Frame superclass to initialize it then setting a local parent variable (you really shouldn't need to do that! Frame does it for you) and then calling the initGUI() method of the new instance (denoted by self). > def initUI(self): > self.parent.title(“TestApp") > self.pack(fill=BOTH, expand=1) And this is the initGUI() method which is just a helper function like any other but, because it's inside the class and has a self parameter is a custom method of your class. It's not obligatory, but is quite common, to have a separate method to initialize the GUI widgets in the window (not least because it allows you to reset the window without restarting the application). In this case it sets the Window title then packs the window into its parent. Recall the containment tree? When you create the instance you must pass a parent into init() and that call to pack() will cause Tkinter to insert your new window under the parent within the tree. In this case the parent will be the top level Window but it could be a dialog box or a sub frame of a larger window. def main(): root = Tk() root.geometry("250x150+300+300") app = test(root) root.mainloop() The main function creates a root object for your GUI using the Tk() function (remember that containment tree?). It sets the initial geometry(size and position) of the window then creates an instance of your Test class passing the root object as the parent. (The self parameter is filled in using more OOP magic by Python. It takes the value of your new object - app in this case.) So at this point your __init__() method gets called as: Test.__init__(app, root) Once everything has been initialized the mainloop() of the root widget is called which starts Tkinter looking for events to process. It will send the events to the lowest level widget it can find - your app widget in this case. But if it cannot find an event handling function/method there it will pass the event up the containment tree (this is the GUI magic bit!) until it finds something that can handle it. If the event reaches the top of the tree(root) without finding a handler then it gets thrown away(usually). Most GUI events in your app are picked up by Frame or root (move, resize, close etc) so you don;t need to provide any code yet. Now we can look at what happens when you a
[Tutor] Help understanding classes
Hello everyone, hope all is well. Was just wondering if I could get some help understanding classes and how they work. What is the point in OOP if I don¹t understand classes, are classes not the heart and soul of OOP? I have been trying to learn classes by practicing with Tkinter building GUIs. Below is my code, which does work. It simply opens a window. I just don¹t understand why it works? Where would the rest of my code go(after I write it of course)? Say, I added code to do something in the window; for example, if I wanted to add buttons and if a button was clicked, execute some linux commands and display the output in the window? I don¹t understand where that code would go. I can easily execute linux commands using subprocess, psutil, os, and even commands, but how does that all work together with classes? I feel like all the code I have written thus far is very linear and simple, and if I can grasp classes I can get out of this stagnate slump. Thank you in advance. from Tkinter import * class test(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title(³TestApp") self.pack(fill=BOTH, expand=1) def main(): root = Tk() root.geometry("250x150+300+300") app = test(root) root.mainloop() if __name__ == '__main__': main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] [OT] Best Practices for Scientific Computing
Hi, I thought this might be worth sharing, especially on a windy, rainy Friday evnening: http://www.plosbiology.org/article/info%3Adoi%2F10.1371%2Fjournal.pbio.1001745 Here are the best practices mentioned in the article: Write programs for people, not computers. A program should not require its readers to hold more than a handful of facts in memory at once. Make names consistent, distinctive, and meaningful. Make code style and formatting consistent. Let the computer do the work. Make the computer repeat tasks. Save recent commands in a file for re-use. Use a build tool to automate workflows. Make incremental changes. Work in small steps with frequent feedback and course correction. Use a version control system. Put everything that has been created manually in version control. Don't repeat yourself (or others). Every piece of data must have a single authoritative representation in the system. Modularize code rather than copying and pasting. Re-use code instead of rewriting it. Plan for mistakes. Add assertions to programs to check their operation. Use an off-the-shelf unit testing library. Turn bugs into test cases. Use a symbolic debugger. Optimize software only after it works correctly. Use a profiler to identify bottlenecks. Write code in the highest-level language possible. Document design and purpose, not mechanics. Document interfaces and reasons, not implementations. Refactor code in preference to explaining how it works. Embed the documentation for a piece of software in that software. Collaborate. Use pre-merge code reviews. Use pair programming when bringing someone new up to speed and when tackling particularly tricky problems. Use an issue tracking tool. Have a great weekend! Regards, Albert-Jan ~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tile Code
On 14/11/14 01:20, niyanax...@gmail.com wrote: You keep sending us your homework but not any of your code. We will not do your homework for you. And we can only guess at what bits you don't understand unless you tell us. Please include your code and a specific question or area of difficulty. If you get an error message include that too. The other issue in this case is that it refers to a graphics module. Which module is that? It is not part of the standard Python library. Statement: 1. The first and last tile in the first row shall be black. 2. The first and last tile in the first column shall be black. 3. The tiles will alternate between black and lemon What happens for 4 tiles? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Tile Code
Statement: 1. The first and last tile in the first row shall be black. 2. The first and last tile in the first column shall be black. 3. The tiles will alternate between black and lemon The task is to write a function to compute and print: the number of tiles needed in the first row (the number of columns) the number of tiles needed in the first column (the number of rows) the total number of tiles needed to cover the floor the gap at the end of each row the gap at the end of each column And then print (using a function): 1. The colored tile pattern to a graphics window a. The pattern should be printed centered in the graphics window, with equal gaps at the end of each row, and equal gaps at the end of each column Use functions to: 1. Read and validate the input values a. Width b. Length c. Tile Size 2. Compute the number of rows, columns, total tiles required, and the size of the gaps at the end of each row and column 3. Print the tile pattern This is my outline but some things I do not know how to do. from graphics import GraphicsWindow x = 10 y = 10 def main() : --> // do stuff --> width = getNumber("Choose a width: ", "Invalid value.", 1, 1000) --> height = getNumber("Choose a height: ", "Invalid value.", 1, 1000) --> win = GraphicsWindow(width, height) --> canvas = win.canvas() --> drawCheckerboard(canvas, x, y, width, height) main() According to the constraints he wants you to use convenient functions. Those would likely be, getNumber() and drawCheckerboard() You want a number between A and B so we have # Prompt user with "msg" to return a number between "min" and "max" otherwise output "err_msg" def getNumber(msg, err_msg, min, max): --> num = min - 1 --> while num < min or num > max --> --> num = input(msg) --> --> if num < min or num > max --> --> --> print(err_msg) // print invalid msg # Draws checkerboard def drawCheckerboard(canvas, x, y, width, height) : --> // more stuff let me know when you get to this part Sent from Windows Mail___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor