Python step-by-step article

Source: Internet
Author: User

Python Advanced Import Importing module

Sys.path: Gets a collection of strings for the specified module search path, which can be placed in a given path, and can be found correctly when import is in the program.

? Import Sys

? Sys.path.append ("")

Re-importing Modules

? Reload (module)

= =, is
    a = [11,22,33]    b = [11,22,33]    >>>a == b    True    >>>a is b    False    >>>a = c    >>>a is c    True

Number within a certain range A is b,true, other range false

Deep copy and shallow copy

? A = [11,22,33]

? b =a

? >>>id (a) ==id (b)

? True

? No data copied, just copy the point to it is a shallow copy

? Import Copy

? c = Copy.deepcopy (a)

? ID (a) differs from ID (c), deep copy

? A = [11,22,33]

? b = [44,55,66]

? c = [A, b]

? D = copy.deepcopy (c)

? E = Copy.copy (c)

? A.append (44)

? >>>C[0]

? [11,22,33,44]

? >>>D[0]

? [11,22,33]

? >>>E[0]

? [11,22,33,44]

Copy.copy () list, ID is also different, but will continue to copy

After changing to tuple, copy.copy (), same ID, tuple immutable type, direct shallow copy

Copy.copy () different functions depending on the variable immutable type

Decimal, binary, octal, hexadecimal conversions

Privatization
    • XX: Public variables

    • _x:from somemodule Import * prohibits importing, class objects and subclasses can access

    • __XX: Double front underline, avoid naming conflicts with attributes in subclasses, cannot access directly externally

    • ___XX___: Double front and back underline, object or property

    • Xx_: Single-post underline to avoid conflicts with Python keywords

###### 1. Adding getter and setter methods to private properties

?

"' Python
Class Money (object):

    def __init__(self):        self.__money = 0    def getMoney(self):        return self.__money    def setMoney(self,value):        if  isinstance(value,int):            self.__money = value        else:            print("error:不是整型数字")

```

?

###### 2. Upgrading getter and Setter methods using property

?

"' Python
Class Money (object):

    def __init__(self):        self.__money = 0    def getMoney(self):        return self.__money    def setMoney(self,value):        if isinstance(value,int):            self.__money = value        else:            print("error:不是整型数字")    money = property(getMoney,setMoney)

```

Note :

  1. T.num whether to call Getnum () or setnum (), according to the actual scene to judge;

  2. If you assign a value to T.num, then it must be called setnum ()

  3. If you are getting the value of t.num, then you must call Getnum ()

  4. Property: The equivalent of encapsulating the method, which makes it easier for developers to set data on attributes

    ?

    "' Python
    Class Money (object):

        def  __init__(self):        self.__money = 0    @property    def money(self):        return self.__money    @money.setter    def money(self,value):        if  isinstance(value,int):            self.__money = value        else:            print("error:不是整型数字")

    ```

    ?

    # # # Iterator

    1. Can iterate objects

    There are several types of data that are directly acting on a For loop:

    One is a collection of data types, such as LIST,TUPLE,DICT,SET,STR, etc.;

    One is generator, including the generator and the generator function with yield.

    These objects that can directly act on a for loop are called an iterative object: Lterable.

    ##### 2. Determine if you can iterate

    You can use Isinstance () to determine whether an object is lterable:

    "' Python
    From collections Import iterable

    isinstance("abc",Iterable)>>>True

    ```

    ?

    ##### 3. iterators

    An object that can be called by the next () function and continually returns the next value becomes an iterator: Iterator

    ? From collections Import Iterator

    ? Isinstance ([],iterator)

    ? >>>false

    ? Isinstance ((x for X in range), Iterator)

    ? >>>true

    ##### 4.iter () function

    Generators are iterator objects, but list, dict, and Str are iterable, but not iterator.

    To change the list, dict, str, etc. iterable to iterator you can use the ITER () function:

    ? Isinstance (ITER ([]), Iterator)

    ? >>>true

    # # # Closure Pack

    "' Python
    #在函数内部再定义一个函数, and this function uses the variables of the outer function, then the function and some of the variables used are called closures.

    def  test(number):    print("----1------")    def test_in(number2):        print("------2----")        print(number-number2)    print("-----3-----")    return test_inret = test(100)ret(1)\>>>----1------    -----3-----    ------2----    99def  test(a,b):    def  test_in(x):        print(a*x+b)    return  test_inline1 = test(1,1)   line1(0)line2 = test(10,4)line2(0)line1(0)

    ```

    ?

    # # # Decorators

    ? def W1 (func):

    ? def inner ():

    ? Print ("----Verifying permissions------")

    ? Func ()

    ? return inner

    ? Def f1 ():

    ? Print ("----F1-----")

    ? def f2 ():

    ? Print ("----F2-----")

    ? Innerfunc = W1 (F1)

    ? Innerfunc ()

    F1 assignment Address, F1 () Call function

    ? def W1 (func):

    ? def inner ():

    ? Print ("----Verifying permissions------")

    ? Func ()

    ? return inner

    ? Def f1 ():

    ? Print ("----F1-----")

    ? def f2 ():

    ? Print ("----F2-----")

    ? F1 = W1 (F1)

    ? F1 ()

    @w1 equivalent to W1 (F1)

    def W1 (func):

    ? def inner ():

    ? Print ("----Verifying permissions------")

    ? Func ()

    ? return inner

    ? @w1

    ? Def f1 ():

    ? Print ("----F1-----")

    ? @w1

    ? def f2 ():

    ? Print ("----F2-----")

    ? F1 ()

    ? F2 ()

    ###### multiple adorners

    ? def makebold (FN):

    ? Def wrapped ():

    ? Print ("----1------")

    ? Return "" + fn () + ""

    ? return wrapped

    ? def makeitalic (FN):

    ? Def wrapped ():

    ? Print ("----2------")

    ? Return "" + fn () + ""

    ? return wrapped

    ? @makeBold # As long as the Python interpreter executes this code, it will be decorated automatically instead of waiting until the call is decorated

    ? @makeItalic

    ? def test3 ():

    ? Print ("--------3-----")

    ? Return "Hello world-3"

    ? ret = TEST3 ()

    ? Print (ret)

    ? >>>----1------

    ? ----2------

    ? --------3-----

    ? Hello world-3

    From the top down, from the bottom to the top decoration

    ? def W1 (func):

    ? Print ("----is decorating 1-----")

    ? def inner ():

    ? Print ("------Verifying permissions 1-----")

    ? def W2 (func):

    ? Print ("----is decorating 2-----")

    ? def inner ():

    ? Print ("----Verifying permissions 2----")

    ? Func ()

    ? return inner ()

    ? @w1

    ? @w2

    ? Def f1 ():

    ? Print ("----f1----")

    ? F1 () #在调用f1之前, has been decorated

    ? >>>----is decorating 2-----

    ? ----are decorating 1-----

    ? ------Verifying Permissions 1-----

    ? ----Verifying Permissions 2----

    ? ----F1----

    ###### decorators decorate with parametric, parameterless functions

    "' Python
    def func (functionname):

        print("----func---1---")    def  fun_in(*args,**kwargs):#定义不定长参数        print("---func_in---1---")        functionName(*args,**kwargs)        print("---func_in---2---")    print("---func---2---")    return func_in@funcdef  test1(a,b,c):    print("----test-a=%d,b=%d,c=%d---"%(a,b,c))@funcdef  test2(a,b,c,d):    print("----test-a=%d,b=%d,c=%d,d=%d---"%(a,b,c,d))test1(11,22,33)test2(44,55,66,77)\>>>----func---1---    ---func---2---    ---func---1---    ---func---2---    ---func_in---1---    ----test-a=11,b=22,c=33---    ---func_in---2---    ---func_in---1---    ----test-a=44,b=55,c=66,d=77---    ---func_in---2---

    ```

    ###### decorator to decorate parameters with return values

    "' Python
    def func (functionname):

        print("---func---1---")    def  func_in():        print("---func_in---1---")        ret = functionName()#保存返回来的haha        print("---func_in---2---")        return ret  #把haha返回到调用处    print("---func---2---")@funcdef  test():    print("----test----")    return  "haha"ret = test()print("test return value is %s"%ret)

    Adorner with parameters

    def  func_arg(arg):    def  func(functionName):        def  func_in():            print("---记录日志-arg=%s--"%arg)            if  arg =="heihei":                functionName()                functionName()            else:                functionName()        return func_in()    return  func@func_arg("heihei")#带有参数的装饰器,能够起到在运行时,有不同的功能def  test():    print("--test--")@func_arg("haha")def  test2():    print("--test2--")test()test2()

    ```

    ?

    # # # Scope

    ###### LEGB Rules

    Builtings, globals, locals, enclosing function,

    Locals: currently located namespace

    Enclosing function: namespaces for outer nested functions (common in closures)

    Globals: Global Variables

    Builtings: Inline

    ##### adding properties and methods dynamically

    Add an attribute class/instance. property = XX

    The Add method does not follow the method above,

    ? Import types. Methodtype

    ? The bound object. function name () = types. Methodtype (name of function, bound object)

    ###### __slots__

    For the purpose of limiting, Python allows you to define a special __slots__ variable to limit the attributes that a class instance can add when defining class:

    "' Python

    class Person (object):
    Slots = ("name", "Age")

    P = person ()
    P.name = "Lao Wang"
    P.age = 20
    #添加其他属性会报错
    ```

    ##### Generator

    Counting on one side of the loop

    ###### Creating a Generator method

    1. Change the [] list generation to () to get the next return value of the generator by the next function

    python def creatNum(): print("-----start-----") a,b = 0,1 for i in range(5): print("----1----") yield b #程序停下来,把yield后面的值返回 print("----2----") a,b = b,a+b print("----3----") print("----stop----") \>>>a = creatNum() \>>>a <generator object creatNum at 0x7f42d27de7d8> \>>>next(a) -----start----- ----1---- 1 \>>>next(a)#等价于a.__next__() ----2---- ----3---- ----1---- 1

    python def test(): i = 0 while i<5: temp = yield i print(temp) i+=1 \>>>t = test() \>>>t.__next__() [out] 0 \>>>t.__next__() None [out] 1 \>>>t.__next__() None [out] 2 \>>>t.send("haha") haha [out] 3

    ##### class as an adorner

    Defines a __call__ method that the class can call directly

classTest (Object):def __init__( Self, func):Print("---Initialize---")Print("Func name is%s"%Func.__name__) Self. __func=Funcdef __call__( Self):Print("---features in adorners---") Self. __func ()@TestdefTest ():#当用Test来装作装饰器对test函数进行装饰的时候, an instance object of test is created first, Func points to test (), func.__name__ function name    Print("---Test---") test ()
Meta class

Class is also an object

To create a class using type

python = type(类名,由父类名称组成的元组(针对继承的情况可以为空),包含属性的字典) Person = type("Person",(),{"num":0}) p1 = Person() \>>>p1.num 0 def printNum(self): print("---num-%d---"%self.num) \>>>Test3 = type("Test3",(),{"printNum":printnum}) t1 = Test3() t1.num = 100 t1.printNum() ---num-100---

__metaclass__ Property
defUpper_attr (future_class_name,future_class_parents,future_class_attr):#遍历属性字典, capitalize the attribute name that is not the beginning of __Newattr={} forName,valueinchFuture_class_attr.items ():if  notName.startswith ("__"): Newattr[name.upper ()]=Value#调用type来创建一个类    return type(future_class_name,future_class_parents,newattr)classFoo (Object, Metaclass=UPPER_ATTR):#设置Foo类的元类为upper_attrBar= "Bip"Print(hasattr(Foo,' Bar '))Print(hasattr(Foo,' BAR ')) F=Foo ()Print(F.bar)
Garbage collection

1. Small integer Object pool

[-5,257] These integer objects are set up well in advance and are not garbage collected. In a python program, all integers that are in this range use the same object

2. Large integer Object pool

3.intern mechanism

    • Small integer shared object, resident memory
    • Single character shared object, resident memory
    • Single word, non-modifiable, default on intern mechanism, common object, reference count of 0, destroy
Garbage collection (GC garbage Collection)

Python is based on a reference counting mechanism, which is supplemented by the two mechanisms of tag-purge and generational collection.

Advantages of the reference counting mechanism:

    • Simple
    • Usability: Once there is no reference, the memory is released directly. The time it takes to process the reclaimed memory is spread to the usual

Disadvantages:

    • Maintain reference count consumption resources

    • Circular references

python list1 = [] list2 = [] list1.append(list2) list2.append(list1)

The reference count of List1 and List2 is still 1, and the memory used can never be recycled.

Linked list reference count, generational collection

1. Case of reference count +1

    • Objects are created, such as a=23
    • object is referenced, such as B =a
    • The object is passed into a function as a parameter, for example, Func (a)
    • Object as an element, stored in a container, such as List1=[a,a]

2. Case of reference count-1

    • The alias of the object is explicitly destroyed, for example del a
    • The alias of the object is assigned a new object, such as a=24
    • An object leaves his scope, such as a local variable in the Func function when the Func function finishes executing (global variable does not)
    • The container where the object resides is destroyed, or the object is deleted from the container

3. View a reference count for an object

python import sys a = "hello world" sys.getrefcount(a) \>>>2

python import gc#gc默认运行 gc.disable()#关闭gc gc.collect()#手动调用collect

##### built-in properties

Common proprietary Properties Description Contact Method
__init__ Constructing initialization functions When an instance is created, it is used when assigned, after __new__
__new__ Properties required to build the instance When you create an instance
__class__ Class where the instance resides instance. __class__
__str__ Instance string representation, readability Print (class property), if not implemented, uses the repr result
__repr__ instance string representation, accuracy class instance carriage return or print (Repr (class instance))
__del__ Destruction Del Delete Instance
__dict__ Instance Custom Properties VARs (instance. __dict__)
__doc__ Class document, subclasses cannot inherit Help (class or instance)
__getattribute__ Property Access Blocker When you access instance properties
__base__ All the parent classes of the class constitute elements Class name. __bases__

# # # Built-in functions

###### Map function

Map (function,sequence[,sequence,...]) List

    • Functions: is a function
    • Sequence: is one or more sequences, depending on the function requires several parameters
    • The return value is a list

"' Python
#函数需要一个参数
Map (Lambda x:x*x,[1,2,3])
# The result is: [1,4,9]

#函数需要两个参数
Map (lambda x, y:x+y,[1,2,3],[4,5,6])
#结果为: [5,7,9]

def f1 (x, y):
return (x, y)
L1 =[0,1,2,3,4,5,6]
L2 =[' Sun ', ' M ', ' t ', ' W ', ' t ', ' F ', ' S ']
L3 =map (F1,L1,L2)
Print (list (L3))
#结果为: [(0, ' Sun '), (1, ' M '), (2, ' t '), (3, ' W '), (4, ' t '), (5, ' F '), (6, ' S ')]

```

##### Filter function

Perform filtering on the specified object

The filter function calls the function function for each element in the sequence parameter sequence, and the result that is returned contains the element that invokes the result as ture.

The type of the return value is the same as the type of the parameter sequence

python filter(lambda x: x%2,[1,2,3,4]) [1,3] filter(None,"she") ‘she‘

##### Reduce function

Reduce takes an element from the sequence in turn and invokes function again with the result of the last call to function. When a function is called for the first time, the function is called with the first element in sequence and the initial as a parameter if the initial parameter is supplied. Otherwise, the function is called with the first two elements in the sequence sequence. Note The function function cannot be none.

"' Python
Reduce (lambda x, y:x+y,[1,2,3,4])
10

Reduce (lambda x,y:x+y,[1,2,3,4],5)
15

Reduce (lambda x, y:x+y,[' AA ', ' BB ', ' cc '), ' DD ')
' DDAABBCC '
Python3 inside the reduce function to be introduced first: from Functools import reduce
```

##### sorted function

"' Python
A = [55,22,77,99]
A.sort ()
>>>a
[22,55,77,99]
A.sort (Reverse=ture)
>>>a
[99,77,55,22]

Sorted ([1,5,4,2])
>>>[1,2,4,5]
Sorted ([1,5,4,2],reverse=1)
>>>[5,4,2,1]
```

# # # Set Set

"' Python
A=[11,55,44,22,11,11]
b = Set (a)
>>>b
{11,55,44,22}
>>>a=list (b)
>>>a
[11,55,44,22]

A = "abcdef"
b = Set (a)
>>>b
{' A ', ' B ', ' C ', ' d ', ' e ', ' f '}
A= "Bdfhuy"
B = Set (A)
>>>b
{' B ', ' d ', ' f ', ' h ', ' u ', ' Y '}
>>>b&b
{' B ', ' d ', ' F '}
>>>b| B
{' A ', ' B ', ' C ', ' d ', ' e ', ' F, ' h ', ' u ', ' Y '}
>>>b-b
{' A ', ' C ', ' E '}
>>>b^b
{' A ', ' C ', ' e ', ' h ', ' u ', ' Y '}
```

##### Functools

###### Partial function

"' Python
Import Functools
def showarg (*args,**kw):
Print (ARG)
Print (kw)

P1=functools.partial (showarg,1,2,3)
P1 ()
P1 (4,5,6)
P1 (a= ' python ', b= ' itcast ')

>>> (a)
{}
(1,2,3,4,5,6)
{}
(a)
{' A ': ' Python ', ' B ': ' Itcast '}
```

###### Wraps function

When using adorners, the decorated function is actually a different function (function names and other functions are changed, and the Functools package provides an adorner called warps to eliminate such side effects.

import functoolsdef note(func):    "note function"    @functools.wraps(func)    def wrapper():        "wrapper function"        print(‘note something‘)        return func()    return wrapper@notedef test():    "test function"    print(‘I am test‘)    test()print(test.__doc__)
Module

Hashlib Encryption algorithm

import= hashlib.md5()#创建hash对象,md5print mm.update(‘itcast‘)#更新哈希对象以字符串参数print(m.hexdigest())#返回十六进制数字字符串

Python step-by-step 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.