See All Titles |
![]() ![]() Code ExamplesThis application subclasses an exception class and executes the commands stored in a file. The filename is asked by the application. Listing 5.1 Configuration File (File configfile.py)1: ### 2: # Program: Configuration File 3: # Author: Andre S Lessa 4: ### 5: 6: ### import modules 7: 8: import exceptions, sys 9: 10: configfile = raw_input("Configuration File: ") 11: 12: class ConfigError (exceptions.Exception): 13: def __init__(self, arg=None): 14: self.args = arg 15: 16: try: 17: try: 18: file = open(configfile) 19: lines = file.readlines() 20: finally: 21: file.close() 22: except: 23: print "Error. Invalid file name." 24: sys.exit() 25: 26: lines[0] = lines[0][:-1] 27: 28: if lines[0] != "CFG2000": 29: raise ConfigError, "Invalid header." 30: 31: lines = lines[1:] 32: 33: for line in lines: 34: try: 35: exec line 36: except LookupError, b: 37: if b.args[0] == "list index out of range": 38: print "Error. Invalid index entry" 39: else: 40: print "Error. Generic LookupError entry" 41: except SystemExit: 42: print "Error. sys.exit() cannot be used." Lines 12-14: The class ConfigError is created. It inherits all the attributes from the exceptions.Exception class. Line 29: Raises our new exception class. In order to test this program, we have to create a file called config.txt that contains the following lines: CFG2000 print print "Configuration File" print "------------------" server = "SRV001" port = 80 print "Server: ", server print "Port: ", port The next interaction shows how to call the program. It also shows the results provided by the program when no exception is raised. C:\ Python>python configfile.py Configuration File: config.txt Configuration File ------------------ Server: SRV001 Port: 80 C:\ Program Files\ Python> This simple program creates a class structure that stores and prints a list of groceries. Listing 5.2 Groceries List (File groceries.py)1: ### 2: # Program: Groceries List 3: # Author: Andre S Lessa 4: ### 5: 6: ### import modules 7: 8: 9: class grocery: 10: "Items that you need to buy at the grocery store." 11: def __init__(self, name, quantity=1): 12: self.name = name 13: self.quantity = quantity 14: 15: items = { } 16: print "Type ENTER when you are done." 17: while 1: 18: name = raw_input("Grocery name: ") 19: if name == "": 20: break 21: quantity = raw_input("%s quantity: " % (name)) 22: if quantity == "": 23: items[name] = grocery(name) 24: else: 25: items[name] = grocery(name,quantity) 26: 27: print "------------------------\ nList of groceries to buy" 28: print "------------------------" 29: 30: for item in items.keys(): 31: print "Grocery : ", items[item].name, 32: print "\ tQuantity: ", items[item].quantity 33: 34: print "---------" Line 9: Declares the grocery class. Line 10: The class's documentation text. Line 11: A default value is defined for the quantity argument. Lines 22-25: Uses a different interface to initialize the object, depending on the information provided. Lines 31-32: Provides access to the object attributes. The next interaction shows how the program works. C:\ Python>python groceries.py Type ENTER when you are done. Grocery name: bananas bananas quantity: 12 Grocery name: apples apples quantity: 6 Grocery name: pears pears quantity: 8 Grocery name: pineapple pineapple quantity: Grocery name: ------------------------ List of groceries to buy ------------------------ Grocery : pineapple Quantity: 1 Grocery : pears Quantity: 8 Grocery : apples Quantity: 6 Grocery : bananas Quantity: 12 --------- C:\ Python> This file introduces two classes and one function that extensively manipulate class methods and attributes. Listing 5.3 Company employees (File company.py)1: ### 2: # Program: Company employees 3: # Author: Andre S Lessa 4: ### 5: 6: ### import modules 7: 8: import types 9: 10: class Employee: 11: "Generic class for all company employees" 12: 13: __employees = 0 14: 15: def __init__(self,name,salary=500.00): 16: self.name = name 17: self.salary = salary 18: self.family = [] 19: Employee.__employees = Employee.__employees + 1 20: 21: def __str__(self): 22: return "employee: %s" % self.name 23: 24: def raisesalary(self, percent): 25: self.salary = self.salary + (self.salary * (1.0/percent)) 26: 27: def job(self): 28: print self.name, "writes Python code." 29: 30: def hasfamily(self): 31: return len(self.family) > 0 32: 33: def addmember(self, name): 34: self.family.append(name) 35: 36: def removemember(self, arg): 37: if len(self.family) > 0: 38: if type(arg) == type(1): 39: self.removemember_int(arg) 40: elif isinstance(arg, types.StringType): 41: self.removemember_str(arg) 42: 43: def removemember_int(self, index): 44: member = self.family[index] 45: del self.family[index] 46: return member 47: 48: def removemember_str(self, name): 49: for member in self.family: 50: if member == name: 51: del self.family[self.family.index(member)] 52: return member 53: 54: def __getitem__(self, index): 55: member = self.family[index] 56: return member 57: 58: class Leader(Employee): 59: "Company's Leader of the employees" 60: def __init__ (self, name): 61: Employee.__init__ (self, name, 1500.00) 62: def job(self): 63: print self.name, "supervises who writes Python code." 64: 65: def totalemployee(): 66: return Employee._employee_employees Line 10: Defines the Employee class. Line 13: Class variable __employees. Line 19: Increments the number of employees. Line 31: Returns a logical value (0 or 1). Lines 36-41: Implements polymorphism by enabling the user to enter both string and integer values. Lines 43-52: Helper methods for the polymorphism implementation. Line 54: Enables the slicing of employees instances. Line 58: Defines a subclass Leader that inherits attributes from the Employee class. Lines 60-63: The __init__() and the job() methods are overwritten. Line 65: Provides a function that returns the total number of employees who are currently part of the class. The following interaction shows how the classes must be used. >>> import company >>> andre = company.employee("Andre") # Creates an employee instance >>> print andre employee: Andre >>> print andre.salary 500 >>> andre.raisesalary(10) # Raises his salary in 10 percent >>> andre.salary 550.0 >>> andre.job() # Shows his job description Andre writes Python code. >>> andre.hasfamily() 0 >>> andre.addmember("Renata") # Add a member to his family >>> andre.addmember("Joao Pedro") # Add a member to his family >>> andre.addmember("Rebecca") # Add a member to his family >>> andre.hasfamily() # Returns 1 or 0 1 >>> andre.family ['Renata', 'Joao Pedro', 'Rebecca'] >>> andre.removemember("Joao Pedro") # Remove string member from list >>> andre.family ['Renata', 'Rebecca'] >>> andre.removemember("Renata >>> andre.family ['Rebecca'] >>> andre.removemember(0) # Remove index member from list >>> andre.family [] >>> andre.addmember("Joao Pedro") >>> andre.addmember("Renata") >>> andre.addmember("Rebecca") >>> andre[0] 'Joao Pedro' >>> andre[1 'Renata' >>> andre[2] 'Rebecca' >>> company.totalemployee()# Shows the total number of employees 1 >>> renata = company.employee("Renata") >>> company.totalemployee() 2 >>> Joao = company.Leader("Joao Pedro") # Creates a leader instance >>> Joao.salary 1500.0 >>> Joao.job() Joao Pedro makes food >>> company.totalemployee() 3 >>>
|
Index terms contained in this sectioncodecompany employees company employees source code employees source code lists company employees source code source code company employees |
© 2002, O'Reilly & Associates, Inc. |