Technology Bookazine 1557 (Sampler)

Page 5

Finish up your UNIX program was about. Well, it is the main distinguishing feature between methods and ordinary functions. Methods, even those that have no other arguments, must have the self variable. It is an automatically populated variable, which will always point to the particular instance of the object that you’re working with. So self.count is a count variable that is exclusive to individual instances of the catCommand object.

The run method We next need to write a method that will execute the appropriate logic depending on whether certain options are set. We’ve called this the run method: def run(self, i, options): #set default options e = “” for line in i: #modify printed line according to options if options.showend: [...last time] if options.shownum: line = “{0} {1}”.format(self.count, line) self.count += 1 print(line, end=e) Notice that we’ve passed the self variable to this method, too. The two other arguments passed to this function are arguments that we’ll pass when we call the method later on, just like with a normal function. The first, i, is going to be a reference to whichever file is being displayed at this moment, while the options variable is a reference to the options decoded by the OptParse module. The logic after that is clear – for each line in the current file, modify the line depending on what options have been set. Either we do as last time, and modify the end character to be “$\n” or we modify the line, using the .format method that we suggested you research last time, to append the count variable, defined in the init method, to the rest of the line. We then increment the count and print the line. The most important part is the use of self. It lets us refer to variables stored within the current instance of the object. Because it’s stored as part of the object, it will persist after the current execution of the run method ends. As long as we use the run method attached to the same object each time we cat a new file in the argument list, the count will remember how many lines were displayed in the last file, and continue to count correctly. It might seem more natural – given the description of methods as individual actions that can be taken by our objects – to split each argument into a different method, and this is a fine way to approach the problem. The reason we’ve done it this way, though, is that we found it meant we could re-use more code, making it more readable and less error-prone. Now all that’s left to do is to tie everything together. We are going to do this by writing a main function. This isn’t actually required in Python, but many programs follow this idiom, so we will too: def main(): [option parsing code ...] c = catCommand() if len(args) > 1:

The completed program isn’t very long, but it has given us a chance to introduce you to many different aspects of the Python language

for a in args: f = open(a, “r”) c.run(f, options) else: c.run(sys.stdin, options) We haven’t filled in the object parsing code from the previous tutorial, because that hasn’t changed. What is new is the c = catCommand() line. This is how we create an instance of a class – how we create a new object. The c object now has a variable, count, which is accessible by all its methods as the self.count variable. This is what will enable us to track the line numbers. We then check to see whether any arguments have been passed. If they have, then we call the run method of the object c for each file that was passed as an argument, passing in any options extracted by OptParse along the way. If there weren’t any arguments, though, we simply call the run method with sys.stdin instead of a file object. The final thing we need to do here is actually call the main function when the program is run: if __name__ == “__ main__”: main() These last two lines are the strangest of all, but quite useful in a lot of circumstances. The name variable is special – when the program is run on the command line, or otherwise as a standalone application, it is set to main; however, when it is imported as an external module to other Python programs, it’s not. In this way, we can automatically execute main when run as a standalone program, but not when we’re importing it as a module. n

“The last thing to do is call the main function when the program runs”

Coding Academy 2018 | 23


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.