def test_module(): assert str(moduletest.ageofqueen) == "78" assert moduletest.printhello() == "hello" cfcpiano = moduletest.Piano() cfcpiano.printdetails()
# For example, the sys.modules dictionary, covered in # "Module Loading" on page 144, holds module objects as its values. # The fact that modules are ordinary objects in Python is often # expressed by saying that modules are first-class objects. # *** The 'import' Statement *** ''' import modname [as varname][,...] ''' # This exmaple: http://sthurlow.com/python/lesson09/ # IMPORTS ANOTHER MODULE see moduletest.py import moduletest print(moduletest.ageofqueen) cfcpiano = moduletest.Piano() cfcpiano.printdetails() # Or one can import only the wanted objects from the module from moduletest import ageofqueen from moduletest import printhello # now try using them (with or without module name) print(ageofqueen) # prints: 78 print(moduletest.ageofqueen) # prints: 78 printhello() # prints: hello moduletest.printhello() # prints: hello # Attributes and module objects '''
# NameError: name 'printhello' is not defined moduletest.printhello() # hello Piano.printdetails() # Traceback (most recent call last): # File "<input>", line 1, in <module> # NameError: name 'Piano' is not defined moduletest.Piano.printdetails() # Traceback (most recent call last): # File "<input>", line 1, in <module> # TypeError: unbound method printdetails() must be called with Piano instance as first argument (got nothing instead) moduletest.Piano().printdetails() # What type of piano? >? grand # What height (in feet)? >? 5 # How much did it cost? >? 2500 # How old is it (in years)? >? 8 # This piano is a/an 5 foot grand piano, 8 years old and costing 2500 dollars. #A more typical way of handling the above function call: cfcpiano = moduletest.Piano() cfcpiano.printdetails() ########################## # ASSIGNING ITEMS TO A LOCAL NAME ########################## timesfour = moduletest.timesfour