Python of the day crash

Source: Internet
Author: User
Tags lua

Python day crash is a cheat paper ~ How can a day ~ just a quick look at some basic

First of all, I am a novice python, only on the Internet to search examples and then use Python to write some analysis files of the script, now work requires, a short time to learn more about Python. This article is not for the full novice, or for Python has a little touch and need to master or some other languages have a certain study of people to see.

First, the implementation process

First of all, Python is compiled and interpreted in the first language, similar to PHP and Java, PHP is compiled into opcode and then interpreted to execute, Java is compiled into a. class file and then executed by the virtual machine, but the compile time is different, PHP and Python are usually compiled and executed at runtime, Java is compiled first, and then compiled. class to execute.

Python at the time of execution, you will first . py the source code in the file is compiled into Python of the Bytecode ( byte code), and then by the pythonvirtual Machine to perform these compilations . bytecode. the standard implementation of Python is written by portable ansic and can be compiled and run on all current mainstream platforms.

As follows:

Test.py Defining a function

#!/usr/bin/python2.6#-*-coding:utf-8-*-def Hello (s):    print S;

Then another python file uses the functions in test.py

#!/usr/bin/python2.6#-*-coding:utf-8-*-from test import Hellohello ("Yang Lingyun")

The output is nothing special, it is the output of a string. The coding part is to specify the encoding, so there is no problem with using Chinese.

will see test.py next to generate TEST.PYC this file, because it is a binary file, Vim-b, again:%!xxd, you can see a bunch of 16 binary things, in fact, Python compiled after the generated bytecode. Files that use test.py do not generate this file.

Understand, the main reason is that the Python file generated after the compilation of bytecode will load into memory execution, the current execution of the file bytecode because in memory, it is generally not necessary to save the file to the hard disk, and the other Python files called, in order to reuse and execute efficiency, the bytecode is preserved as a file, In the next execution, compare the last modified time of the. py and. pyc files, and if they are consistent, execute the PYc file, and if the inconsistencies are recompiled again, plainly for reuse and cache.


Ii. Types of data

Python is a dynamic type strongly typed language, and if anyone adds a string and an integer, it will be an error.

>>> print "DF" +5traceback (most recent call last):  File "<stdin>", line 1, in <module>typeerror: Cannot concatenate ' str ' and ' int ' objects

    • Python, like PHP, Lua, and so on, built-in types provide common data structures such as lists (list), dictionaries (dictionary), Strings ( string ), providing great convenience.
    • Python is a dynamic type, because Python's variable definitions do not require a specified type, unlike C and Java, where each variable binds to a data type, and, like PHP, a variable can give multiple types of data. At the same time, at compile time, Python does not check whether the object has the called method or property, only to run to check, so it may fail
    • Say Python is a strongly typed language, above has an example, not like PHP in the calculation of the automatic type conversion, before the article also wrote, for PHP, the weak type of language, in fact, in the conversion of a lot of holes in the inside ~
    • Python and PHP, Java type, do not need to like C as the underlying memory management, Python has a GC, and the use of object reference count, and based on reference counting to implement automatic garbage collection.

All things in Python are objects, with the following basic data types

1, none, indicates that the object is null, none is false compared to 0 or false

2, Boolean type, True, False,none, 0 in any numeric type, empty string "", Empty tuple (), empty list [], empty dictionary {} are treated as False, and custom types, if __nonzero__ () or __len__ () are implemented Method and the method returns 0 or FALSE, its instance is also treated as false. I test the use of python2.7.3, measured down, if compared with false, 0==false is ture, the other with false to do the comparison or false, but if the 0, () and so on in the if condition, the condition to determine the result is false.

In addition Python does not use &&, | | These operations use English words such as and, or, not.

3, integral type, long integer, floating point type, integer 4 byte, long integer type is much larger than C long, it can be considered that the maximum support is infinite.

4, the Python comparison of the cattle is to support the plural, what is the plural, have learned the mathematics of the affirmation of contact ~

5, string, single quote double quotes no difference, 3 quotation marks are used to represent multiple lines of content, and preserve formatting

>>> print ' haha      ... One ...   Three ' haha one  twothree

Use \ To escape the horse is similar to other languages, the string preceded by R or R means that the following string is not escaped by default.

The string supports slicing str[start:end:step], which means that from start to end, step is sliced for step size, and a negative number is used to slice back and forth.

6, List [],list, the concept of sequential array, list has append, Extend, insert, index, remove, Del, pop and other operations

>>> array=[1,2,3,4,5,6]>>> print array[2:5:2][3, 5]>>> print len (array) 6>>> print Array.index (3) 2

Because all things are objects, arrays are available in several ways, while arrays support slicing array[start:end:step], which means that from start to end, step is sliced for step size, and negative values are used to slice back and forth.


7, tuple (), tuple, similar to the list, but once initialized can no longer be modified, fast
8. Set {},set, definition in mathematics, unordered, non-repeating, support arithmetic
>>> seta={1,2,3,4,5}   >>> setb={3,4,5,6,7}   >>> Print Seta-setbset ([1, 2]) >> > Print Seta & Setbset ([3, 4, 5]) >>> Print Seta | Setbset ([1, 2, 3, 4, 5, 6, 7])

9, Dictionary {},{key:value}, like JSON, note that key to be immutable type, such as Integer floating-point and tuple, dictionary has del obj[' a '];obj.clear ();

>>> obj={5:4, ' a ': ' B '}>>> print obj[' a ']b
Other

Python comments using #

The end of each line can be used; semicolons can also be used without using; You can write multiple statements on one line but not recommend

Code blocks and indents are important, and the average person knows.


Third, grammar

Python and Lua are a bit like, there are a lot of syntax sugar, writing code is sometimes very concise, of course, it will not understand.

    • Defining functions using

def foo (param1, param2):      Lalalala

    • Import other PY code

Use import or from xxx import xxx

    • Print, separated by commas, the output will have a space, also can be similar to the C printf formatted output

>>> print ' A ', 1a 1>>> print '%d%d '% (2,3) 23

    • Assign value

>>> (a,b,c,d,e,f,g) =range (7) >>> print a,b,c,d,e,f,g0 1 2 3 4 5 6

    • Traverse

>>> list = [1,2,3,4,5]>>> list = [Ele * for ele in list]>>> print list[2, 4, 6, 8, 10]

Methods like Array_map in PHP

Dictionary traversal using Dic.keys ();d ic.values ();d ic.items ();


    • Ternary operators, like Lua, Python does not?: Ternary operators, using and and or combinations can achieve the purpose of the ternary operator, the principle is, or return two operands of the first true (true) operand, and and is A is true returns B,a to False returns a.

>>> a=true>>> b=1>>> c=2>>> print A and B or C1


    • The sense of a lambda like a C macro or inline function, or the meaning of a JS closure

>>> print (lambda x:x*2) (3) 6>>> print (lambda x:x*x*3.14) (3) 28.26>>> print (lambda x:x*x*x) ( 3)   27>>> f=lambda x:x*x*x>>> F (2) 8
    • Looping statements
While True:    passelse:    Pass

For I in range (0, 5):    print Ielse:    Pass

The pass represents an empty statement, and the range function believes that there is some understanding, else is the statement executed at the end of the loop, and if there is a break in the loop, the Else statement is not executed.

    • Key parameters

There's a funny thing in Python.

>>> def foo (a=1, b=2, c=3): ...     Print A,b,c ... >>> foo (b=5, c=6) 1 5 6
Usually if we make a lot of default parameters, once only need to pass the value of the last parameter, it is tragic to write a lot of parameters default value, so much easier.

    • __name__

The value of __name__ is usually the file name, and if the value is __main__, it is the file that the user executes, which is similar to the main entry.


    • Common methods

About list, tuple, set and other commonly used methods are not here to introduce, Python articles and documents a lot of search, use when check, here only introduce basic ~


Four, object-oriented programming

Write a Simple object-oriented example

First file imtest.py

Print __name__class Knight:    "I am Strong Knight"    Count = 0    def __init__ (self, Name, HP):        Knight.count + = 1        self.name = name        self.__hp = hp        print ' Knight comes ' def die (self    ):        self.__hp = 0< C11/>def gethp (self):        return SELF.__HP

A second file test.py

Import Imtestprint __name__class holyknight (imtest. Knight):    "I am Great holyknight"    def __init__ (self, name, HP, MP):        Imtest. Knight.__init__ (self, name, hp)        SELF.__MP = MP        print ' holyknight comes ' kn = holyknight (' Cloudy ', ten, 5) print Holy Knight.__doc__print Imtest. Knight.countprint kn.nameprint kn.gethp () print kn.__hp

The final output is

Imtest__main__knight comesholyknight Comesi am Great Holyknight1cloudy10traceback (most recent call last):  File " test.py ", line page, in <module>    print Kn.__hpattributeerror:holyknight instance have no attribute ' __hp '

It contains a few points,

    • How to define a class, use class, static variable definition in a class, method definition, how to inherit, how to use the parent class method, which can be seen in the sample code.
    • The way the class method is instance.method(arguments) called is. It's equivalent to Class.method(instance, arguments) calling, which is the same as Lua.
    • A static variable in a class, and a method definition, which is similar to the LUA implementation object-oriented approach, is invoked using A.func () when using a method of a class instance, whereas a reference to the object of a is actually passed into the method as the self parameter, implementing the function of the this pointer in the method. This piece needs to be understood, if you are familiar with Lua is simple.
    • __init__ and __del__, respectively, are constructors and destructors, the default methods and properties are public, and the properties that begin with the double underscore in the example are private and cannot be read directly.
    • The __doc__ can be placed under a class or method definition using a string to describe the object.


V. Other

These are not described in Python crash ~ but I think it is a very important thing in Python syntax, follow up slowly thoroughly understand.

    • Exception handling, try: Except...else...finally ...
    • Assert statement, similar to assert in other languages
    • Yield statement, used within an iterator function, to return an element. Since Python version 2.5. This statement becomes an operator, interested can search the relevant introduction, look at the feeling with the co-process a bit like, specific still need to understand.
    • With statement to run a block of statements in a scene. For example, the statement block is run before it is locked and then released after the statement block has finished running. Familiar.
Tail

Looking for information, reading, writing code test, spent more than 3-5 hours, the Python language level has a general understanding, after the beginning to understand the next web.py framework, there is time to carefully study the other Python syntax



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.