Python Quick Tutorials (supplemental): Python tips

Source: Internet
Author: User

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".

Python
123456789 def Lib_func(a): return a + ten def lib_func_another(b): return b + if __name__ = = ' __main__ ': Test = 101 Print(lib_func(test))

We import the testlib above in the user.py.

Python
12 import TestLib Print(TestLib. Lib_func(+))

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:

Like what:

Python
12 import TestLib as t print(t. Lib_func(+))

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:

Python
12 from TestLib import lib_func Print(lib_func )

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

Like what:

Python
12 from TestLib import * Print(lib_func )

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.

Python
12 import inspect Print(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:

Python
12 a = [1,2,3] Print(hasattr(a,' append '))

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

Python 
123 a = [1, Span class= "CRAYON-CN" >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:

Python
1 Print(list. __base__)

Use Chinese (and other non-ASCII encodings)

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

Python
12 #coding =utf8 Print("How are You?") ")

can also be used in the following ways:

Python
12 #-*-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

Python
123 Print(0b1110) # Binary, starting 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:

Python
123 print(int("1110", 2)) print(int("Ten", 8)) print(int("2A", + ))

Comments

Comments within a line can start with #

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

Python
12345678910 " this is demo "  def func () :     # print something     print ( "Hello world!"  # use Print () function  # main func (

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:

Python
12 import sys print(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.

All-in-one programmer Exchange QQ Group 290551701, gather a lot of Internet elite, technical director, architect, Project Manager! Open source technology research, Welcome to the industry, Daniel and beginners are interested in engaging in IT industry personnel to enter!

Python Quick Tutorials (supplemental): Python tips

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.