Python supplement 02 my python tips Python quick tutorial

Source: Internet
Author: User

Author: vamei Source: http://www.cnblogs.com/vamei welcome reprint, please also keep this statement. Thank you!

 

Here are some tips I have learned when using python. These skills are frequently used when I use python. I recorded it in my notebook in a very fragmented manner. Now I will sort it out and share it with you. It also serves as a supplement to the python quick tutorial.

 

Import Module

In python, the import declaration is often used to use objects defined in other modules (that is, other. py files.

1) Use_ Name __

When writing a python library module, we often run some test statements. When thisProgramWhen the database is imported, we do not need to run these test statements. One solution is to comment out the test statement in the module before import. Python has a better solution, that is, using _ name __.

Below is a simple library program testlib. py. When testlib. py is run directly, __name _ is"_ Main __". If it is imported, __name _ is"Testlib".

 
DefLib_func ():ReturnA + 10
DefLib_func_another (B ):ReturnB + 20
If _ Name __='_ Main __': Test= 101Print(Lib_func (TEST ))

Import testlib above in user. py.

 
ImportTestlibPrint(Testlib. lib_func (120 ))

You can try not to use if _ name __= '_ main _' in testlib. py and compare the running result.

 

2) more import usage

Import testlib as test# Reference the testlib module and rename it to T

For example:

 
ImportTestlib as tPrint(Tb. lib_func (120 ))

From testlib import lib_func# Only reference the lib_func object in testlib,And skip the testlib Reference Field

This reduces the memory usage of the referenced module.

For example:

 
FromTestlibImportLib_funcPrint(Lib_func (120 ))

From testlib import *# Reference all objects in testlib and skip the testlib Reference Field

For example:

 
FromTestlibImport*Print(Lib_func (120 ))

 

Query

1) query function parameters

When you want to know which parameters a function will receive, you can use the following method to query.

ImportInspectPrint(Inspect. getargspec (func ))

 

2) query the attributes of an object

BesidesDir ()To query the attributes of an object, we can use the following built-in (built-in) function to check whether an object has a certain attribute:

Hasattr (OBJ, attr_name)# Attr_name is a string

For example:

A = [1, 2, 3]Print(Hasattr (,'Append'))

 

2) query the Class and Class Name of the object

 
A = [1, 2, 3]PrintA._ Class __PrintA._ Class __._ Name __

 

3) query the parent class

We can use_ Base __Attribute to query the parent class of a class:

Cls. _ base __

For example:

 
Print(List._ Base __)

 

Use Chinese (and other non-ASCII codes)

Add# Coding = utf8For example:

#Coding = utf8Print("How are you?")

You can also use the following methods:

 
#-*-Coding: UTF-8 -*-Print("How are you?")

 

Indicates binary, octal, and hexadecimal numbers.

In version 2.6 or later

Print(0b1110)#Binary, starting with 0 BPrint(0o10)#Octal, starting with 0 oPrint(0x2a)#Hexadecimal format, starting with 0x

For earlier versions, you can use the following method:

Print(INT ("1110", 2 ))
Print(INT ("10", 8 ))
Print(INT ("2a", 16 ))

 

Note

The comment in a line can be#Start

The comments of multiple rows can be'''Start'''End, for example

'''This is demo'''DefFunc ():#Print somethingPrint("Hello world!")# Use print () function#MainFunc ()

Comments should be included with the program blockAlignment.

 

Search Path

During import, Python searches for modules in the search path ). For example, the above import testlib requires testlib. py to be in the search path.

You can view the search path using the following method:

 
ImportSysPrint(SYS. Path)

You can add or delete elements in SYS. path when running python. On the other hand, we can addPythonpathEnvironment variable to add a search path for python.

Next we will add/home/vamei/mylib to the search path:

$ Export pythonpath = $ pythonpath:/home/vamei/mylib

You can add the front line of commands ~ /. Bashrc. In this way, we will change the search path for a long time.

 

Combine scripts with command lines

You can use the following method to run a Python script. After the script is run, you can directly enter the python command line. The advantage of this is that the script object will not be cleared and can be called directly through the command line.

$ Python-I script. py

 

Install non-standard packages

Python standard library is installed with python. When we need a non-standard package, we need to install it first.

1) use Linux repository (Linux environment)

This is a good starting point for installing Python additional packages. You can search for possible Python packages in Linux repository (for example, search for matplot in Ubuntu Software Center ).

2) use Pip. Pip is a package management program that comes with python. It connects to Python repository and searches for possible packages.

For example, use the following method to install, uninstall, or upgrade Web. py:

$ Pip Install Web. py

$ Pip uninstall web. py

$ Pip install -- upgrade Web. py

If your python is installed in a non-standard path (using $ which python to confirm the path of the python executable file), such as/home/vamei/util/Python/bin, you can use the following method to set the path of the PIP installation package:

$ Pip install -- install-option = "-- prefix =/home/vamei/util/" Web. py

3) Compile from source code

If the above method cannot find the library you want, you may need to compile from the source code. Google is often the best starting point.

 

If there are new gains in the future, we will add them to this blog post.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.