python学习笔记

Modules

Modules aren't really meant to do things (such as printing text) when they're imported. They are meant to define things, such as variables, functions, classes, and so on. And because you need to define things only once, importing a module several times has the same effect as importing it once.

If you insist on reloading your module , you can use the built-in function reload. It takes a single argument (the module you want to reload) and returns the reloaded module. This may be useful if you have made changes to your module and want those changes reflected in your program while it is running. The best thing in most cases is simply to stay away from module reloading.

Telling the interpreter where to look if you place your modules somewhere else, edit sys.path is not a common way to do it. The standard method is to include your module directory (or directories) in the environment variable PYTHONPATH.

Telling the module whether it's being run as a program on its own or being imported into another program. To do that, you need the variable __name__; In the "main program", the variable __name__ has the value '__main__'. In a imported module, it is set to the name of that module.

If you have a data structure that is too big to fit on one line, you can use the pprint function from the pprint module instead of the normal print statement. pprint is a pretty-printing function, which makes a more intelligent printout.

Packages

To structure your modules, you can group them into packages. a package is a directory. To make Python treat it as a package, it must contain a file (module) named __init__.py. To put modules inside a package, simply put the module files inside the package directory.

To find out what a module contains, you can use the dir function.

__all__  variable defines the public interface of the module. it tells the interpreter what it means to import all the names from this module.  from module import *  you get the functions list in the __all__ variable.

The sys module gives you access to variables and functions that are closely linked to the Python interpreter.

The os module gives you access to several operating system services.

Sets , Heaps , and Deques 

time , random , shelve and re

 

FILES

Read method read the entire file as a string , readlines method read the file into a list of string, in which each string is a line.

 

 

Generators

A generator is a kind of iterator that is defined with normal function syntax. Any function that contains a yield statement is called a generator.

it will behave quite differently from ordinary functions. The different is that instead of returning one value, as you do with return, you can yield several values, one at a time. Each time a value is yielded (with yield) , the function freezes; that is, it stops its execution at exactly that point and waits to be reawakened. When it is, it resumes its execution at the point where it stopped.

list comprehension: g = ((i+2)**2 for i in range(2,27))

generator comprehension: g = [(i+2)**2 for i in range(2,27)]

A generator is a function that contains the keyword yield. When it is called, the code in the function body is not executed. Instead, an iterator is returned. Each time a value is requested, the code in the generator is executed until a yield or a return is encountered. 

Generator Methods

A relatively new feature of generator is the ability to supply generators with values after they have started running. 

The outside world has access to a method on the generator called send, which works just like next, except that it takes a single argument (the "message" to send)

 

The Iterator Protocol

The __iter__ method returns an iterator, which is any object with a method called next, which is callable without any arguments. When you call the next method, the iterator should return its "next value". If the method is called, and the iterator has no more values to return, it should raise a StopIteration exception.

 

The Basic Sequence and Mapping Protocol

Sequences and mappings are basically collections of items. To implement their basic behavior(protocol):

__len__(self): This method should return the number of items contained in the collection.

__getitem__(self, key): This should return the value corresponding to the given key.

__setitem__(self, key, value): This should store value in a manner associated with key.

__delitem__(self, key): This is called when someone uses the del statement on a part of the object, and should delete the element associated with key.

 

super Function: It works only with new-style classes, but you should be using those anyway. It is called with the current class and instance as its arguments, and any method you call on the returned object will be fetched from the superclass rather than the current class. 

 

To make your classes "new-style", you should either put the assignment __metaclass__ = type at the top;

 

If you want to find out whether a class is a subclass of another, you can use the built-in method issubclass:

>>> issubclass(SPAMFilter, filter)

If you have a class and want to know its base classes, you can access its special attribute __bases__:

>>> SPAMFilter.__bases__

(<class __main__.Filter at 0x171e40>)

 

Note that instead of using hasattr in an if statement and accessing the attribute directley, I'm using getattr, which allows me to supply a default value (in this case None) that will be used if the attribute is not present.

 

To list the contents of a module, you can use the dir function.

>>> import exceptions

>>> dir(exceptions)

['ArithmeticError', 'AssertionError', 'AttributeError', ...]

 

If you have caught an exception but you want to raise it again (pass it on, so to speak) , you can call raise without any arguments.

 

When you retrieve a method from an instance, the self argument of the method is automatically bound to the instance (a so-called bound method). However, if you retrieve the method directly from the class (such as in Bird.__init__) , there is no instance to which to bind. Therefore, you are free to supply any self you want to. Such method is called unbound.

 

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

 

Python官方文档   6.1.2 The Module Search Path

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path, sys.path is initialized from these locations:

  1. the directory containing the input script (or the current directory).
  2. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  3. the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the begining of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. 

The variable sys.path is a list of strings that determines the interpreter's search path for modules. You can modify it using standard list operations:

1 >>> import sys
2 >>> sys.path.append('/ufs/guido/lib/python')
View Code

 

  

 

posted @ 2015-10-12 14:53  林大勇  阅读(207)  评论(0编辑  收藏  举报