Notes--python (function related)

        ---Function annotation----
            In [1]: def clip(test:str,max_len:'int>0'=80) ->str:
               ...: pass
               ...:
                Parameter annotation: test:str , Max_len:'int>0' 
                return value annotation: ->str
            In [2]: clip.__annotations__
            Out[2]: {'test': str,'max_len':'int>0','return': str }
                View annotations:                 __annotations__ , where return is the return value annotation
                
        ---- double method-----
            __all__
all.py 
                    __all__=['x','y','test']
                    x=2
                    y=3
                    z=4
                    def test():
                            print(‘test’)
                            
                            
                test.py
                    from all import *
                    print(x)
                    print(y)
                    print(z)
                    test()
                    
                输出:
                    2
                    3
                    Traceback (most recent call last):
                      File "test.py", line 4, in <module>
                        print(z)
                    NameError: name 'z' is not defined
                    
                修改test.py:
                    from all import *
                    from all import z
                    print(x)
                    print (y)
                    print (z)
                    test ()

                Output:
                    2
                    3
                    4
                    test

            __enter__ and __exit__
                implement the __enter__ and __exit__ methods, that is, support the context manager protocol. The context manager is an object that supports the context manager protocol, and it is born for with. When the with statement starts to run, the __enter__ method is called on the context manager object. After the with statement runs, the __exit__ method
            
            __repr__ and __str__
                __str__ function and usage will be called on the context manager object :
                  1. __str__ function: display the instance object in the form of a string in a custom format To improve readability.
                  2. The instantiated object will call the __str__ method by default when printing or, if the class does not override this method, the __str__ method of the parent class object will be called by default.
                  3. The internal __str__ method of object is pass, so the memory address is printed. If the current class overrides this method, the overridden method will be called automatically.
                The function and usage of
                  __repr__ 1. If you use the IDE software to operate __repr__, the function is exactly the same as __str__, both of which are instance visualization displays
                  . 2. During development, if users need to visualize the content of the instance, they only need to rewrite __str__ or __repr_ _One of the methods is fine. If there are both, __str__ is called by default.
                  3. The difference between the two is to use the command line operation:
                     After 3.1__str__ is rewritten, if the direct instance stu is entered, it will display the address of the stu instance in memory, which is different from print(stu).
                     3.2 After rewriting __repr__, if you directly instantiate stu and press Enter, the effect is the same as using print(stu), the content is returned, not the memory address.       
                            
            __version__
                In [19]: import urllib3

                In [20]: urllib3.__version__
                Out[20]: '1.25.8'            
                            
        ----Decorator------
            · Closure: 
              An inner function is defined in an outer function, and an inner function is used in the inner function Temporary variables of the outer function, and the return value of the outer function is a reference to the inner function. This constitutes a closure.
            The function decorator is executed immediately when the module is imported, and the decorated function only runs when it is explicitly called
            . The decorator returns the decorated function intact, but this technique is not useless. Many Python web frameworks use such decorators to add functions to a central registry, such as the registry that maps URL patterns to functions that generate HTTP responses. This registration decorator may or may not modify the decorated function.
            
            --property 
                class Student:
                    def __init__(self,name):
                        self.__name = name
                    @property #Turn the function into the property of the object (read-only)
                    def name(self):
                        return self.__name

                    @name.setter #When modifying the name attribute, trigger this function
                    def name(self,new_name):
                        if type(new_name) is str:
                            self.__name = new_name

                a1 = Student("Tom")
                print(a1.name)
                a1.name = 'jerry'
                print(a1.name)

            
        ----高阶函数与列表推导式---
            In [7]: def fact(num):return num*num
            In [8]: map(fact,range(6))
            Out[8]: <map at 0x7f1667778be0>
            In [9]: list(map(fact,range(6))
               ...: )
            Out[9]: [0, 1, 4, 9, 16, 25]
            In [10]: [fact(n) for n in range(6)]
            Out[10]: [0, 1, 4, 9, 16, 25]
            
            In [14]: list(map(fact,filter(lambda n: n%2, range(6))))
            Out[14]: [1, 9, 25]

            In [15]: [fact(n) for n in range(6) if n%2]
            Out[15]: [1, 9, 25]
            
        ----Built-in reduction function----
            sum and reduce The general idea is to apply an operation to the elements of the sequence successively, accumulate the previous results, and reduce a series of values ​​into one value.
            all and any are also built-in reduction functions. 
            all(iterable)
              If each element of iterable is true, return True; all([]) returns True. 
            any(iterable) 
              returns True as long as there are elements in iterable that are true; any([]) returns False

        ----Built-in functions---
            --repr
                >>>s ='RUNOOB'
                >>> repr(s)
                "'RUNOOB'"
                >>> dict = {'runoob':'runoob.com','google ':'google.com'};
                >>> repr(dict)
                "{'google':'google.com','runoob':'runoob.com'}"
                >>>
            ---isinstance
                In [1] : ss='1111'
                In [3]: isinstance(ss,str)
                Out[3]: True    
            
        ---defense variable parameters ---
            error example:
                In [22]: class Test:
                    ...:     def __init__(self,li=[]):
                    ...: self.li = li
                    ...:
                # because t1, t2 none parameter passing, using default li pointing to the same actual list of
                In [23]: t1 = Test ()

                In [24]: t2=Test()

                In [27]: t1.li.append(1) #Adding
                elements to li of t1 will affect li of t2
                In [28]: t2.li
                Out[28]: [1]
            Correct example:
                In [29]: class Test:
                    ...: def __init__(self,li=None):
                    ...: if li:
                    ...: self.li=li
                    ...: else: #If no parameters are passed, each instance will be created A new empty list
                    ...: self.li=[]

                In [30]: t1=Test()

                In [31]: t2=Test()

                In [32]: t1.li.append([1,2,3,4])

                In [33]: t2.li
                Out[33]: []
        
    ----Data type----                 --Dictionary
        :
            dictionary sort: #by
                value
kv_list = sorted(dic.items(),key=lambda x: x[1],reverse=True)                 #press
                key
#kv_list = sorted(dic.items(),key=lambda x:x[0],reverse=True)
                key_list = []
                value_list = []
                #traverse kv tuples The composed list
                for key, value in kv_list: key_list.append
                    (key)
                    value_list.append(value)
                    
            Set the dictionary default value:
                message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
                count = {}
                for character in message:
                    count.setdefault(character, 0)
                    count[character] = count[character] + 1
                print(count)
                或:
                    count = {}
                    for char in message:
                        if char in count:
                            count['char']+=1
                        else:
                            count['char']=1
                            
            字典update()方法:
                >>> dict = {'Name': 'Zara', 'Age': 7}
                >>> dict2 = {'Sex': 'female' }
                >>> dict.update(dict2)
                >>> dict
                {'Name': 'Zara', 'Age': 7, 'Sex': 'female'}
                >>> dict3 = {'Age': 8 }
                >>> dict.update(dict3)
                >>> dict
                {'Name': 'Zara', 'Age': 8, 'Sex': 'female'}

            Compare two dictionaries
                >>> import operator
                >>> operator.eq(dict2,dict3)
                False

            Modify the dictionary
                during traversal : modify the dictionary elements during the dictionary traversal, and report an error RuntimeError: dictionary changed size during iteration. I learned that the dictionary elements cannot be modified during the traversal.
                Solution: Change the traversal condition to a list
                for zone in list(dic.keys() ):
                    if not dic[zone]:
                        del(dic[zone])
                Method 2, copy a dictionary:
                import copy
                d = {'a': 1,'b': 2,'c': []}
                for key, value in copy.deepcopy(d).items():
                    print(key, value)
                    if not value:
                        del d[key]
                print(d)
            
            modify dictionary key:
                dict={'a':1,'b':2 }
                dict["c"] = dict.pop("a")

        --列表:
            --append和extend
                In [16]: ls = [1,2,3,4]
                In [17]: ls.append([5,6,7,8])
                In [18]: ls
                Out[18]: [1, 2, 3, 4, [5, 6, 7, 8]]

                In [21]: li = [1,2,3,4]
                In [22]: li.extend([5,6,7,8])
                In [23]: li
                Out[23]: [1, 2, 3, 4, 5, 6, 7, 8]

            --列表的深浅copy
                浅copy:
                    li = [1,2,['aa','bb']]
                    li2 = li.copy()
                    li[0] = 'a'
                    li[2][0] = 'cc'
                    print(li,li2)
                    >>>>['a', 2, ['cc', 'bb']] [1, 2, ['cc', 'bb']]
                深copy:
                    import copy
                    li = [1,2,['aa','bb']]
                    li3 = copy.deepcopy(li)
                    li[0] = 'a'
                    li[2][0] = 'cc'
                    print(li,li3) --List                 In [8]: l1=[1,2,3]                 #Compare the elements in the list in order
                
            comparison size

                In [9]: l2 = [1,2,4]

                In [10]: l3=[1,3,1]

                In [11]: l1>l3
                Out[11]: False

                In [12]: l1<l2
                Out[12]: True #If the
                element types are not the same, an error will be reported
                In [13]: l4=[1,'2',5]

                In [14]: l4>l1
                ---------------------------------------------------------------------------
                TypeError                                 Traceback (most recent call last)
                <ipython-input-14-918a6d16635b> in <module>
                ----> 1 l4>l1

                TypeError:'>' not supported between instances of'str' and'int' #Comparison of
                lists with different lengths
                In [15]: l5=[1,2,3,4]
                In [18]: l5<l1
                Out[ 18]: False

                --Iterator         :
            Take the last element:
                >>> *_,last =(i for i in range( 1111111 ))
                >>> last
1111110
                or:
                    >>> for ls in (i for i in range(1111111) ):
                    ... continue
                    ...
                    >>> print(ls)
                    1111110
            read in batches:
                #Put 0-1111 into the list of length 100
                it = (i for i in range(1111))
                start = 1
                li = []
                for i in it:
                    li.append(i)
                    start +=1
                    if start == 100:
                        print(li)
                        start = 1
                        li = []
                #Must have, otherwise the last loop did not process
                print(li)
            to add sequence numbers to the elements in the iterator:
                g = (i for i in range(33 ))
                for i,v in enumerate(g,0):
                    print(i,v)

                0 0
                1 1
                ...
                32 32
            

Guess you like

Origin blog.csdn.net/weixin_42573277/article/details/114837933