10 minutes to learn the advanced syntax of Python

Source: Internet
Author: User
Tags create directory

(0) Catalogue

Installing Ubuntu's blood-vomiting experience under VMware

0 Basic Learning Shell programming

The magical magic of makefile under Linux

Linux debugging artifact--GDB

10 minutes Learn the basic types of Python

distributed version management artifact--git

Three states of git files & git ssh key issues

10 minutes to learn the advanced syntax of Python

Configure SSH password-free access and Linux hotkey, restart, kill process

A comparison between the indefinite length parameters of Java and the indefinite length parameters of Python

One: Cause

(1) as a glue language Python, is ubiquitous, rapid development of prototype sites, large data processing and other fields of application is very wide

(2) Iters, who has been learning C-+ + or Java, is easy to learn python, especially for the beginner-level Python syntax

(3) Just beginning to learn python, practice python, may feel particularly awkward-there is no method {}, in recent years by: and strict indentation in the code snippet, the separation of the program segment

(4) Some Python source code sharing, please download

Second: Python Advanced language

(1) Differences between%r and%s in Python-- %r processing objects with the Rper () method--%s processing objects with the STR () method

In some cases, the result of both processing is the same, for example, to deal with an int type object:

Text = "I am%d years old"%  print "I said:%s."% text  print "I said:%r."% text I said:i am-years old.  I said: ' I am years old './/%r Add single quotation marks to the string
(2) if __name__ = = ' __main__ ' in Python: role

#hello. Pydef SayHello ():    str= "Hello"    print (str), if __name__ = = "__main__":    print (' This is main of module ') hello.py "')    SayHello ()
Python as a scripting language, each module written in Python can contain more than one of the main functions like C, but there are some differences between this __main__ in Python and C, which are mainly reflected in:

1) When the module is executed separately , such as performing the above Hello.py:python hello.py alone, the output
This is main of the module "hello.py"
Hello
Can be understood as "if __name__==" __main__ ":" This sentence is consistent with the main () function in C, that is, as a portal;

2) When the module is introduced by another module , the block represented by the "if __name__==" __main__ ":" is not executed, because when the module is referenced by another module, its __name_ The value of _ will change and the value of __name__ will be the name of the module. For example, after you import the hello in the Python shell, look at hello.__name__:
>>> Import Hello
>>> hello.__name__
' Hello '
>>>

3) Therefore, in Python, when a module is executed as a whole, the value of moduel.__name__ will be "__main__", and when a module is referenced by another module, module.__name__ will be the module's own name , of course, when a module is referenced by another module, it does not need an executable entry in itself, Main.

if __name__ = = ' __main__ ': print ' This program was    being run by itself ' else:    print ' I am being imported from anothe R module '

(3) My own question: I can understand the concept of object-oriented programming, the sense that python can be solved with a module, why should there be something like class?

1) First answer __: because the class members of Python are public, publicly accessible public, and lack of proprietary private properties like the Orthodox object-oriented language , then use __ to simulate the private properties . These __ properties are often used internally and are usually not rewritten. And not read. Add 2 underline purpose, one is not and common public attribute duplicate name conflict, second, not let the object user (non-developer) arbitrary use.

2) Object-oriented is a method of improvement, not using the object module does not work, just as C language also with similar, no object in the way of providing modules, can also develop anything. But the use of objects can improve code reuse, improve development efficiency, reduce the work of developers. To put it simply, object-oriented is similar to a factory making a plaster sculpture:

Class is the equivalent of a mold, object objects are equivalent to the mold poured out of sculpture, sculpture can be copied in large quantities. To modify the sculpture is to modify the mold, not to change the finished sculpture.

From the data point of view, a sculpture may consist of a plurality of base parts, hand, foot, head, these are the data, of course, the object has the action, all the functions of the object is its action, such as running, eating, barking.

The most common, student class, provides some data, name, telephone, age, these are the data, the student union "answer" "eat", "consumption", "Contact" "hands" these are the actions of delivering messages.

This combination of data and action is an object that the class takes to standardize the data and actions. Once again, this same class of objects does not require duplication of development.

(4) __init__ (initialization operation) and __del__ (end operation, such as closing of file and closing of database) in Python:

1) There is no dedicated constructor and destructor in Python, but it is generally possible to perform initialization and deletion operations in __init__ and __del__ respectively, which can be used to construct and deconstruct the alternative. There is also a __new__ that is used to customize the creation of classes, but requires a certain configuration and is not discussed here.

2) The member functions of the class are equal to public, but the default starts with __ as a private variable, although it is private, but we can also access it by some means , that is, Python does not have a true private variable. Such as:
Because of the particularity of Python, global member variables are shared, so instances of the class do not allocate content space specifically for it, similar to static, as shown in the following example.

Test 1:# Encoding:utf8class Newclass (object):    num_count = 0 # All instances share this variable, i.e. no    def __init__ (Self,name) is assigned to each instance individually:        self.name = name        Newclass.num_count + = 1        print name,newclass.num_count    def __del__ (self):        newclass.num_count-= 1        Print "Del", Self.name,newclass.num_count    def Test ():        print "AA" AA = Newclass ("Hello") BB = Newclass ("World") cc = Newclass ("AAAA") print "over" Hello 1World 2aaaa 3OverDeException l Hello 2AttributeError: "' nonetype ' object have no Attri Bute ' Num_count ' in <bound method newclass.__del__ of <__main__.  Newclass object at 0x01af18d0>> ignoredexception attributeerror: "' nonetype ' object have no attribute ' Num_count '" in <bound method Newclass.__del__ of <__main__. Newclass object at 0x01af1970>> ignored
We find that Num_count is global, when each instance is created, __init__ () is called, and the value of Num_count is increased by one, and when the program finishes, all instances are refactored, called __del__ () but an exception is thrown at this point. This exception occurs when you view the exception as "Nonetype", which is when the Newclass has been garbage collected.

But is the question coming? Why is that? In accordance with the experience of C + + and other languages, should not be so ah! After finding the data, we found that Python's garbage collection process is different from the common language, and Python is garbage collected in dictionary order, rather than in the order of creation. So when the system is recycling resources, it will be in the order of the class name A-za-z, in turn, we cannot control the process here.

So, to continue looking, we can also access the class itself through self.__class__, and then access its own shared member variable, the Self.__class__.num_count, to replace Newclass.num_count in the class with self.__ Class__.num_count compile and run as follows:

# Encoding:utf8class Newclass (object):    num_count = 0 # All instances share this variable, that is, the    def __init__ (self,name) is not assigned to each instance individually:        Self.name = Name        Self.__class__.num_count + = 1        print name,newclass.num_count    def __del__ (self):        self . __class__.num_count-= 1        print "Del", Self.name,self.__class__.num_count    def Test ():        print "AA" AA = Newclass ("Hello") BB = Newclass ("world") cc = Newclass ("AAAA") print "over" perfect! We have handled this problem perfectly!
(5) Global variables and local variables in Python

A variable is not shared inside the function and outside the function, especially when the = (equal sign) is present, but a variable can be shared between different blocks within the same function see

(6) Python read and write files efficiently

1) write multiple lines- file_object.writelines (list_of_text_strings)

Note that calling Writelines writes multiple rows at a higher performance than using write one-time writes.

2) in the processing of log files, often encounter such a situation: The log file is huge, it is not possible to read the entire file into memory for processing, such as the need to process a 2GB log file on a machine with a physical memory of 2GB, we may want to process only 200MB of content at a time.

In Python, the built-in File object directly provides a readlines (sizehint) function to accomplish such a thing. Take the following code as an example:

File = open (' Test.log ', ' r ') Sizehint = 209715200   # 200Mposition = 0lines = File.readlines (sizehint) while not File.tell ()-position < 0:position = File.tell () #Python文件操作tell () Method: This method simply returns the current position of the file with the read/write pointer in the file. Lines = File.readlines (sizehint)

each call to the ReadLines (Sizehint) function returns approximately 200MB of data, and the return is necessarily the complete row data, in most cases the number of bytes returned is slightly larger than the value specified by Sizehint (except for the last call ReadLines (sizehint) function. Typically, Python automatically adjusts the value of the user-specified sizehint to an integer multiple of the internal cache size.

(7) Python file Read method

Python provides basic functions and the necessary ways to manipulate files by default. You can do most of the file operation using a file object.
Open function: To read or write to a file, it must be opened using the Python built-in open () function. This function creates a file object that will be used to invoke other support methods associated with it:

Syntax: File object = open (file_name [, access_mode][, Buffering])

1) Parameter details:

The File_name:file_name parameter is a string value that contains the name of the file that you want to access.

Access_mode:access_mode decides that the file must be opened, i.e., read, write, append, etc. the possible values are given in the table below for a complete list of patterns . This is an optional parameter and the default file access mode is read (R).

Buffering: If the buffer value is set to 0 o'clock, no buffering will occur. If the buffer value is 1, the row buffer is accessed by a file to execute. If the specified buffer value is an integer greater than 1, the buffering action is made with the size of the indicated buffer . If negative, the size of the buffer is the system default (the default behavior).

2) mode description

R opens a file as read-only. The file pointer is placed at the beginning of the file. This is the default mode.
Rb Opening a file can only be read in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+ open for reading and writing files. The file pointer will be at the beginning of the file.
rb+ Opens a file for reading and writing binary formats. The file pointer will be at the beginning of the file.
W open a file to write only. Overwrite the file if the file exists. If the file does not exist, it is created to write a new file.
Wb Opening a file can only be written in binary format. Overwrite the file if the file exists. If the file does not exist, it is created to write a new file.
w+ Open the file for writing and reading. Overwrite the existing file if the file exists. If the file does not exist, a new file is created to read and write.
wb+ Opens a file for writing and reading in binary format. Overwrite the existing file if the file exists. If the file does not exist, a new file is created to read and write.
a will open the append file. The file pointer is at the end of the file. That is, the file is in attach mode. If the file does not exist, it creates a new file to write to.
Ab The appended binary format file opens. The file pointer ends at the end of the file. In other words, the file is in append mode. If the file does not exist, it creates and writes a new file.
a + opens to append and read files. The file pointer ends at the end of the file. The file will be in append mode. If the file does not exist, it creates and reads and writes a new file.
ab+ Open two append and read binary format files. The file pointer ends at the end of the file. The file will be in append mode. If the file does not exist, it creates and reads and writes a new file.

3) file operation:

Os.mknod ("test.txt") Create an empty file
fp = open ("Test.txt", "w+") opens a file directly and creates a file if the file does not exist
fp.read ([size]) #size为读取的长度, in bytes
Fp.readline ([size]) #读一行, if size is defined, it is possible to return only part of a row
Fp.readlines ([size]) #把文件每一行作为一个list的一个成员 and returns the list. In fact, its internal is through the Loop call ReadLine () to achieve. If you provide a size parameter, size is the total length of the read content, which means that it may be read only to a portion of the file.
Fp.write (str) #把str写到文件中, write () does not add a newline character after Str
Fp.writelines (seq) #把seq的内容全部写到文件中 (multi-line write-once). This function simply writes faithfully and does not add anything behind each line.
Fp.close () #关闭文件.  Python will automatically close files after a file is not used, but this feature is not guaranteed and it is best to develop a habit of shutting them down. If a file is closed and then manipulated, it generates VALUEERROR
Fp.flush () #把缓冲区的内容写入硬盘

Fp.fileno () #返回一个长整型的 "file label"
Fp.isatty () #文件是否是一个终端设备文件 (on UNIX systems)
Fp.tell () #返回文件操作标记的当前位置, starting with the origin of the file
Fp.next () #返回下一行 and shifts the file action marker to the next line. When a file is used for a statement such as for ... in file, it is called the next () function to implement the traversal.
Fp.seek (Offset[,whence]) #将文件打操作标记移到offset的位置. This offset is generally calculated relative to the beginning of the file and is generally a positive number. However, if the whence parameter is provided, whence can be calculated from scratch for 0, and 1 for the current position as its origin. 2 means that the end of the file is calculated as the origin. Note that if the file is opened in a or a + mode, the file action tag is automatically returned to the end of the file each time the write operation is made.
Fp.truncate ([size]) #把文件裁成规定的大小, the default is the location that is cropped to the current file action tag. If the size of the file is larger, depending on the system may not change the file, it may be 0 files to the corresponding size, it may be some random content to add.

(8) Directory operation:

Os.mkdir ("file")                   Create directory
Copy file:
Shutil.copyfile (" Oldfile "," NewFile ")       Oldfile and newfile can only be files
shutil.copy (" Oldfile "," NewFile ")            oldfile can only be a folder, NewFile can be a file, or it can be a target directory
Copy folder:
Shutil.copytree ("Olddir", "Newdir")        olddir and newdir can only be directories, and Newdir must not have
Rename files (directories)
Os.rename ("Oldname", "newname")   The     file or directory is used to
move files (directories)
Shutil.move ("Oldpos", "Newpos")   
Delete Files
Os.remove ("File
Delete directory
Os.rmdir ("dir") can only delete empty directories
Shutil.rmtree ("dir")     empty directories, contents of the directory may be deleted
Conversion directory
Os.chdir (" Path ")   change path

 2) Add all Picture names under Folder ' _fc '

Python code:

#-*-Coding:utf-8-*-import reimport osimport time#str.split (String) Split string # ' connector '. Join (list) composes the list of strings Def change_name ( Path):    Global I    if not os.path.isdir (path) and not Os.path.isfile (path):        return False    if Os.path.isfile (path):        File_path = os.path.split (path) #分割出目录与文件        lists = File_path[1].split ('. ') #分割出文件与文件扩展名        file_ext = lists[-1] #取出后缀名 (list slice operation)        img_ext = [' bmp ', ' jpeg ', ' gif ', ' psd ', ' png ', ' jpg ']        if file_ext in Img_ Ext:            os.rename (path,file_path[0]+ '/' +lists[0]+ ' _fc. +file_ext)            i+=1 #注意这里的i是一个陷阱        #或者        #img_ext = ' bmp|jpeg|gif|psd|png|jpg '        #if file_ext in Img_ext:        #    print (' OK---' +file_ext)    elif os.path.isdir (path): For        x in Os.listdir (path):            Change_ Name (Os.path.join (path,x)) #os. Path.join () is useful for path processing


10 minutes to learn the advanced syntax of Python

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.