Python Basics Summary and Practice

Source: Internet
Author: User
Tags python script

About Python
    • Python is a dynamic interpretive programming language that compiles the source code into bytecode when the module is loaded, which is interpreted by the virtual machine PVM, where interpretation execution is the main reason for the low performance of Python;
    • Python is written in C and can be used in conjunction with C,c++,java and other languages: Java implementation Jython on Python, specific reference: https://docs.python.org/2/tutorial/ Index.html, and. NET Interoperability ironpython,https://ironpython.codeplex.com/
Compile execution

Compile usually occurs when the module is loaded, the compiler will first compile the source code into bytecode, save in the PYc file, if you use the-o parameter, can generate Pyo file, is a simple optimization of the PYc file;

For the PYc file, the compilation process is as follows:

    • Check the file Magic Mark, magic is a special number, calculated by the Python version number, as the PYc file check mark;
    • Check if the time stamp and source file modification time are the same to determine if recompilation is required;
    • Loading modules;

For a py file, the compilation process is as follows:

    • An AST (abstract syntax tree) analysis of the source code;
    • Compile the analysis results into pycodeobject;
    • Save the Magic, source code modification time, Pycodeobject to the PYc file;
    • Loading modules;

Execution can use the Eval and EXEC functions, eval () is used to execute an expression, and exec executes a code fragment, execfile () dynamically executes a py file;

Pyhton Foundation and Practice

This paper mainly introduces some basic but important knowledge in Python language, such as Python object, function, class, regular expression, code conversion, and so on.

Object

All objects

Everything in Python is an object, each object contains a standard header, and the header information consists of a reference count and a type pointer.

"Reference count" is the main garbage collection mechanism in PVM, and whenever an object is referenced, it is incremented after the scope or call Del is manually released, and the count is recovered by 0 o'clock;

The type pointer can be used to explicitly know the type of the object, point to the type object, and include its inheritance and static member information;

You can use sys.getrefcount (x) to view the object's reference count;

Type (x) and x.__class__ to view object types;

Hex (ID (x)) returns the object memory address;

For a variable-length object, its head will have a field that records the number of elements;

X=10sys.getrefcount (x)  #查看x引用计数, the form of attendance increased by one count; import typestypes (x)  #查看x的类型信息; x.__class__  #__class__ Gets the object type through the type pointer;

Object type

Immutable type: None,bool,int,float,long,complex,string,unicode,tuple,frozenset;
Variable type: List,dict,set

#boolint (True) # 1int (False) # 0 #float ' float defaults to double precision and may not accurately represent decimal fractional ' float (' 0.1 ') * = = float (' 0.5 ') # Falseround (' 2.675 ', 2) # 2.67#decimal can precisely control the number of digits, generally with decimal instead of Floatfrom decimal import decimaldecimal (' 0.1 ') * = = Decimal (' 0.5 ') # True # Str,unicode "need to be aware of coding problems, using decode (), encode () method, a project using different types of coding, it is easy to cause error ' ' Import Logginglogger = Logging.getlogger (' Test ') Logger.info ('%s is not%s '% (U ' Test kanji ', ' Test Kanji ')) #Error, mix two different types of encodings # python2.x The default encoding is ASCII, in general the need for transcoding operations, in most cases, we will be in the Python script header default encoding is set to utf-8#-*-coding:utf-8-*-import Syssys.getdefaultencoding () # ascii# string concatenation, in general: Join > '%s%s ' > +, string preceded by ' r ', meaning not escaped; #dict # for large dictionaries, it is recommended to use iterators instead of keys (). Values (), items () method, reduce memory overhead d={' a ': ' xxx ' ... D.iterkeys (), D.itervalues (), d.iteritems () #求两个dict差集d1 = {' A ': 1, ' B ': 2}d2 = {' B ': 2, ' C ': 3}v1 = D1.viewitems () v2 = D2.viewitems () V1 & v2, v1 | V2, V1-v2, vi ^ v2 # equivalent to Set#dict is a hash table, default is unordered, if ordered dictionary, you can use Ordereddictfrom collections import Ordereddictod = Ordereddict () od [' a '] = ' QQQ ' od[' b '] = ' BBB ' for K,v in Od.items (): PrintK,v # Output #set # in order of addition: (A is B) or (hash (a) = = Hash (b) and EQ (a)) #要将自定义类型放入set, you need to override the __hash__ and __eq__ methods Class User (Object) : Def __init__ (self, name): Self.name = name def __hash__ (self): return hash (self.name) def __eq_ _ (Self, Other): "If not" other "or not" isinstance (Other, User): return false return self.name = = Oth Er.name
An expression

Regular expressions

Regular expressions appear basically in any language and are one of the necessary skills for development, and Python regular expressions are described in https://docs.python.org/2/library/re.html;

#IP地址匹配import redef check_ip (IP): Pattren = R ' ^ (25[0-5]|2[0-4]\d|1\d{2}|[ 1-9]\d| [0-9]) \.xxx$ ' #不全, left like if Re.match (pattern, IP): return True return false# the script that synchronizes data from the Zimbra mailbox to ad is an application instance of an expression: def get_mai L_attrs (self, mail_info): pattern = R ' ^cn:|^displayname|^mail:|^zimbraace:.*owndistlist$|^ (?!        Zimbra). *@ ' attrs = {} attrs[' managedBy '] = [] Split_info = Mail_info.split (' \ n ') for line in Split_info:                If Re.match (pattern, line): item = Line.strip (). Split (': ') if item[0] = = ' Zimbraace ':                    _id = Item[1].split () [0] if _id in self.id_mail: _mail = self.id_mail[_id]            attrs[' ManagedBy '].append (_mail) else:print ' Error,%s has no mail '% _id Elif len (item) > 1:attrs[item[0]] = item[1] else:if ' members ' not I n attrs:attrs[' members ') = [] attrs[' members '].APpend (Item[0]) #在字符串中使用正则表达式, if you do not use the ' R ' tag, you need to use double escape; 

  Statement

Note the else in loops and exceptions, such as: While...else...,for...else...,try...except...else...finally...,else is executed when the loop exits normally, Executes when except does not catch an exception;
List-derived

#举例说明列表推导式的应用def Test (x):    return x**2a = [Test (x) for x in Xrange (ten) if x%2]b = [text (x) for x in open (' Number.txt ', ' R ')] #生成字典c = {C:ord (c) for C in ' ABC '}
D = {D:CHR (d) for D in ' 123 '} #enumerate使用for idx,num in enumerate ([x for x in range]): print "index[{0}] = {1}". f Ormat (idx, num)
Function

The function is not overloaded in the same namespace (determined by __dict__[name] uniqueness) and always has a return value, which returns none by default;

Reference delivery

Python is passed by reference, whether it is an assignment or a function parameter, whether it is a mutable type or an immutable type;
The difference between passing by reference and by value: A reference pass passes a memory address, and a value pass passes a copy of the current value;

A = 10b = 10hex (ID (a)) = = Hex (ID (b))    #Truea is b    #True # function parameter pass, need to note the order, the default parameters must be after the positional parameters, *args and **kwargs must be after the default parameters; def Test (A, B, c=10, d= ' ww ', *args, **kwargs):    print args,kwargs# The default parameter is the object that is generated when the function is created with Def, and the subsequent call function will reuse this object, such as after the first call to test, A is [1 ], after the second call, A is [1,1];def test (a=[]):    a.append (1)    print hex (ID (a))    print a

#对于可变对象, the deepcopy can be used for deep copying, copy.deepcopy (x);

  Name space

The Python namespace can be understood as a name/object dictionary of system and custom objects;

A python variable is a string object that, together with the target object, forms a Name/object association in the namespace, which determines the scope and lifetime of the object;

The variable has no type, the object has, the function of the variable is only to associate with the target object in the namespace at a certain moment;

Globals () Gets the module level namespace, locals () Gets the current context namespace;

The namespaces of other modules can be accessed through <module>.__dict__;

Object Query Order follows LEGB principle, locals, enclosing, globals, __builtins__

Common functions

Python has a number of commonly used functions that can be called directly, such as Lambda,map,zip, and so on, which are no longer detailed.

Class

There are two types of class models in the Python 2.X version, Classic class and New-style Class,classic class support for multiple inheritance, but have been discarded by Python 3.0, and we recommend using New-style class when using classes. That is, the class that inherits object.

When accessing members in a class, the member lookup order: instance.__dict__, class.__dict__, baseclass.__dict__;

Python's built-in class method: GetAttr (obj, name[, default]), SetAttr (obj, name, value), hasattr (obj, name), delattr (obj, name);

Python built-in class properties: __dict__,__name__,__doc__,__module__,__bases__, etc.;

Property

Python built-in function property () can implement attributes;

Class Test (object):         def get_name (self):        return self.__name    def set_name (self, value):        self.__name = Value    def del_name (self):        del self.__name     name = Property (Get_name, Set_name, Del_name) class Test2 (object ):         user_id = property (lambda self:self._user_id)    user_name = property (lambda self:self._user_id, Lambda Self, Value:setattr (self, ' _user_name ', value))

  Garbage collection

Python's garbage collection mainly refers to the reference count, tag cleanup and generational recovery as a supplement, understand the garbage collection process to help write code is not easy to cause memory leaks; Priority: reference count > tag purge and generational recycle JSON and time module
#JSON与Python对象之间的转换json. Dumps (x) #encoding的过程, converts the Python object x encoding to a JSON string json.loads (x) #decoding的过程, Converts a JSON string x decoding to a Python object  #time模块 #python has two ways of representing time, timestamp, and array form. #常用函数time. Clock () #第一次执行获取当前程序的执行时间, then gets the time it takes to run from the first to the current program; Time.sleep () #单位为秒time. CTime () # Converts a timestamp to a time string time.localtime ([seconds]) #将时间戳转换为当前时区的数组形式time. Mktime (tuple) #将数组形式time对象转换为时间戳time. Strftime (format [, tuple]) #将数组形式time对象转换为指定格式化形式time. Strptime (string, format) #将时间字符串根据指定格式转换为数组形式time对象time. Time () #获取当前时间的时间戳  # Gets the absolute path of the current file Os.path.dirname (Os.path.abspath (__file__))

  

Python Basics Summary and Practice

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.