Python Supplement Python Tips

Source: Internet
Author: User

Vamei source: Http://www.cnblogs.com/vamei Welcome reprint, Please also keep this statement. Thank you!

Here are some tips I've accumulated when using Python. These tips are often used by me in the Python process. It was a very fragmentary note in a notebook, now sorted out, and shared with you, also as a supplement to the Python quick tutorial.

Import Module

The import declaration is often used in Python to use objects defined in other modules (that is, other. py files).

1) Use __name__

When we write a Python library module, we often run some test statements. We do not need to run these test statements when this program is being used as a library import. One workaround is to comment out the test statements in the module before Import. Python has a more graceful solution, which is to use __name__.

The following is a simple library program Testlib.py. When running testlib.py directly, __name__ is "__main__". If it is import, __name__ is "TestLib".

def Lib_func (a):    return a + 10
def lib_func_another (b):    return B + 20
if __name__ = = ' __main__ ': test = 101 Print (lib_func (test))

We import the testlib above in the User.py.

Import Testlibprint (testlib.lib_func (120))

You can try not to use if __name__== ' __main__ ' in testlib.py and compare the running Results.

2) more ways to use import

Import TestLib as test # referencing the TestLib module and renaming it to T

Like what:

Import TestLib as Tprint (t.lib_func (120))

From TestLib import Lib_func # References only Lib_func objects in TestLib and skips TestLib reference fields

The benefit of this is to reduce the memory footprint of the referenced module.

Like what:

From TestLib import Lib_funcprint (lib_func (120))

From TESTLIB Import * # References all objects in TestLib and skips TestLib reference fields

Like what:

From TestLib import *print (lib_func (120))

Inquire

1) parameters of the query function

When we want to know what parameters a function will receive, you can use the following method to Query.

Import Inspectprint (inspect.getargspec (func))

2) querying the properties of an object

In addition to using Dir () to query the properties of an object, we can use the following built-in (built-in) function to confirm whether an object has a property:

Hasattr (obj, Attr_name) # attr_name is a string

For example:

A = [1,2,3]print (hasattr (a, ' Append '))

2) the class and class name to which the query object belongs

A = [1, 2, 3]print a.__class__print a.__class__.__name__

3) querying the Parent class

We can use the __base__ property to query the parent class of a class:

cls.__base__

For example:

Print (list.__base__)

Use Chinese (and other non-ascii Encodings)

In the first line of the Python program, add#coding=utf8,例如:

#coding =utf8print ("how are you?" ")

can also be used in the following ways:

#-*-coding:utf-8-*-print ("how are you?" ")

Represents 2 binary, 8 binary and 16 binary digits

In the 2.6 or higher version, the following is the way to express

Print (0b1110)    # binary, beginning with 0b print (0o10)       # octal, beginning with 0o print (0x2A)       # hex, starting with 0x

If this is an earlier version, you can use the following method:

Print (int ("1110", 2))
Print (int ("10", 8))
Print (int ("2A", 16))

Comments

Comments within a line can start with #

Multiple lines of comments can start with ' ', End with ', for example

' This is demo ' def func ():    # print something    print ("Hello World!") # Use print () function# mainfunc ()

The comment should be aligned with the program block in which it resides.

Search Path

When we import, Python looks for the module in the search path. For example, import TestLib above requires testlib.py in the search path.

We can see the search path in the following ways:

Import Sysprint (sys.path)

We can add or remove elements from the Sys.path while Python is running. On the other hand, we can add a search path to Python by adding pythonpath environment variables to the Shell.

Below we add/home/vamei/mylib to the search Path:

$export pythonpath= $PYTHONPATH:/home/vamei/mylib

You can add the front line command to the ~/.BASHRC. In this way, we have changed the search path for a long time.

Scripting and command line binding

You can run a Python script using the following method, and go directly to the Python command line after the script has finished running. The advantage of this is that the object of the script is not emptied and can be called directly from the command Line.

$python-i. script.py

Installing non-standard packages

Python's Standard library is installed with Python. When we need non-standard packages, we must install them First.

1) using Linux repository (linux Environment)

This is a good starting point for installing a Python add-on Package. You can find Python packages that may exist in Linux repository (such as searching for Matplot in Ubuntu software center).

2) Use Pip. Pip is a Python-brought package manager that connects to Python repository and looks for packages that might exist in it.

For example, use the following methods 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 nonstandard path (using $which python to confirm the path to the Python executable file), such as/home/vamei/util/python/bin, you can set the path of the Pip's installation package using the following method:

$pip install--install-option= "--prefix=/home/vamei/util/" web.py

3) Compile from source code

If the above methods are unable to find the library you want, you may need to start compiling from the source Code. Google is often the best place to Start.

If there is a new harvest in the future, it will be added to this blog Post.

Python Supplement Python Tips

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.