Package, exception handling

package:

Through the use of package is a 'module name' python modules organized manner namespace. It is a collection of modules

Such as creating a directory

The module does not have the same name conflict and the packets A packet B, Aa and Ba as from two namespaces

# map () function call to the first parameter argument function to function each element in the sequence, each new list function returns a return value of the function.

import os
os.makedirs('glance/api')
os.makedirs('glance/cmd')
os.makedirs('glance/db')
l = []
l.append(open('glance/__init__.py','w'))
l.append(open('glance/api/__init__.py','w'))
l.append(open('glance/api/policy.py','w'))
l.append(open('glance/api/versions.py','w'))
l.append(open('glance/cmd/__init__.py','w'))
l.append(open('glance/cmd/manage.py','w'))
l.append(open('glance/db/models.py','w'))
map(lambda f:f.close() ,l)
Create a directory
#文件内容

#policy.py
def get():
    print('from policy.py')

#versions.py
def create_resource(conf):
    print('from version.py: ',conf)

#manage.py
def main():
    print('from manage.py')

#models.py
def register_models(engine):
    print('from models.py: ',engine)
document content

1. Whether import from ... import form or forms, all in the import statement (not in use) encountered a little, should alert the first time: This is the only package import syntax

2. The package is a directory level (folder level), the folder is used to compose py file (nature package is a directory containing an __init__.py file)

When the import file 3. import, generate namespace name from file Import package, the name of the namespace generated from the same document, i.e. __init__.py the packet, the packet is essentially introduced in the import file

Emphasize:

  1. In python3 in, even if no package __init__.py file, import the package is still not being given, but in python2, the next package must have the file, or import the package error

  2. Create the package was not intended to run, but was introduced into use, remember that package is just a form of modules only, namely bag module

Reference blog: 
blog: www.cnblogs.com / Eva-J / Articles / 7,292,109 .html # _label7

Introducing the package

note:

1. Import-related statements about the package is also divided into import and from ... import ... are two, but no matter what, no matter what position, when you import must follow a principle: when importing a little all the the left point must be a package, otherwise illegal. It may have a series of points, such as item.subitem.subsubitem, but must follow this principle.

2. For the introduction, in use there is no such limit, the package may be left point, modules, functions, classes (which can be called its own properties manner points).

3. Comparison import item and from item import scenario name is:
if we want to directly use the name that you must use the latter.

import Import

import glance.db.models as models
models.register_models('mysql')

from...import

1 from glance.db import models
2 models.register_models('mysql')
3 
4 from glance.db.models import register_models
5 register_models('mysql')

 

__init__ file, reads the file when each packet init imported, the imported modules can be written in the file

Either way, as long as any other part of the first import package or packages will in turn execute __init__.py file in the package (we can both print a line in the file contents of each packet to verify) this file can be empty, but you can also store some initialization code for the package.

 from glance.api import * cooperate with __all__

When talking about the module, we have already discussed all imported from one module *, where we study a package from import all *.

Here is all you want to import from the package api, the fact that the statement will only import api package __init__.py file name under defined, we can define in this file __all___:

# Defined in __init__.py
__all __ = [ 'x', 'func', 'policy'] 
In this case we glance that the sibling file execution from glance.api import * to import content of __all__
glance/                   

├── __init__.py      

├── api                  

│   ├── __init__.py   __all__ = ['policy','versions'] 

│   ├── policy.py

│   └── versions.py

├── cmd               __all__ = ['manage']    

│   ├── __init__.py

│   └── manage.py    

└── db                __all__ = ['models']              

    ├── __init__.py

    └── models.py



from glance.api import *
policy.get()
View Code

Absolute and relative import import:

Introducing absolute path: intuitive, trouble
opposing Road King introduced:. From import db db introduced in the current directory, the package can be moved, as long as it can find the package bag can not be used in a module inside the package

For example: We want to import glance / cmd / manage.py at glance / api / version.py in
In Glance / API / version.py 

# absolute introduced 
from glance.cmd Import Manage 
manage.main () 

# opposing introduced 
from ..cmd .. # Import Manage represented upper directory. Current directory 
manage.main ()
glance/                   

├── __init__.py      from glance import api
                             from glance import cmd
                             from glance import db

├── api                  

│   ├── __init__.py  from glance.api import policy
                              from glance.api import versions

│   ├── policy.py

│   └── versions.py

├── cmd                 from glance.cmd import manage

│   ├── __init__.py

│   └── manage.py

└── db                   from glance.db import models

    ├── __init__.py

    └── models.py
Absolute imports
the Glance /                    

├── __init__.py       from . Import API #. indicates the current directory
                      from . Import cmd
                      from . Import db 

├── API                   

│ ├── __init__.py   from . Import Policy
                      from . Import versions 

│ ├── Policy. Py 

│ └── versions.py 

├── cmd               from . Import manage 

│ ├── __init__.py 

│ └── manage.py     from ..api Import Policy    
                     # .. is the parent directory, would like to manage in use the method policy will need to return to the previous directory to find api package glance down import policy from api 

└── db                from . import models

    ├── __init__.py

    └── models.py
Relative imports

Exception Handling:

IndexError: Wrong index 
KeyError: key errors 
NameError: Name error 
SyntaxError

# Once the program error has occurred, it stopped in the wrong place, no longer continue, in order that the program does not report an error, do not affect the execution, with the try statement

the try : # program as normal execution, execution errors encountered the except 
     # program 
      RET = int (the INPUT ( " Number The >>>> " )) 
      Print (RET * ' * ' ) 
the except ValueError: # Capture ValueError error 
     Print ( " you enter content is incorrect " ) 
the except NameError:
    Print ( 'you enter the wrong') #except support multi-statement

except Exception as error: (Universal abnormal): Any error can not be caught, usually on the face of the wrong type except the last sentence of
    print ( 'ni wrong', error)

else: # no exceptions when executed else in the code, can be used successfully sent will be displayed after a successful time as sending mail
  print ( "----------")

finally: # Code regardless of whether an exception will be executed, such as when used to open the file, close the file in the final
    print ( '======') behind the code will no longer perform normal when it comes to return, and there will first finally execute the contents inside, in return return
    () # after opening the file f.close, finally closed

 



 

Guess you like

Origin www.cnblogs.com/huxl1/p/10991210.html