Python Learning notes functions and classes

Source: Internet
Author: User

Python-like functions are also available for reuse only if the value of a piece of code is not reused can be used without a function

A general function can be defined like this:

defFunc (a,b=123,*arg,**args): forXinchArg#Arg is a list        Printx forX, yinchArgs.items ():#args is a dict        Printx, yPrint 'A:', aPrint 'B:', Bfunc (1,1,2,3,4,c=1,d=2) Results:234C1D2A:1B:1

Where A is the positional (required) parameter and B is an optional parameter

ARG is a parameter that accepts no limit, and Arg becomes a list when accepted.

Args is accepted a=1,b=2 ... this parameter, after receiving, args becomes a dict

Here are some function-related exercises (including some file operations),

" "Define a function Xulie (dirname,info) Parameter: dirname: path name, info: Data that needs to be serialized, function: serializes the info data to a random file in the dirname path. " "#Call the system function Os.listdir to get all the file names of the corresponding paths, store them in a list#then randomly get a file name in the list using random to change the fileImportRandomdefXulie (dirname,info): List_dir_name=[]     forXinchOs.listdir (dirname): List_dir_name.append (x) temp_name=list_dir_name[random.randint (0, Len (list_dir_name)-1)] F=open (Dirname+temp_name,'AB') F.write (info) f.close () Xulie ('d:\\test\\','This is a test')
defFunc_3 (name=none,**Kargs): Result=[]    ifLen (Kargs) >0: forX, yinchKargs.items (): Result.append ((x+':'+y)) result.insert (0, name)returnresultPrintFunc_3 (name='Lilei', age=' -', city='HK')
Results [' lilei ', ' city:hk ', ' age:20 ']

Class: A class like Java itself also has a constructor (__init__, class instantiation Call), destructor (__exit__, exit context Call, General and __enter__ method), there is a __del__ magic method, Called when Del deletes an instance of the class. There are also static methods that are called directly through a class call, rather than an instance of the class.

classText_sort (object):def __init__(self):Print 'This is init'    def __enter__(self):Print 'This is enter'    def __exit__(self,type,value,traceback):#Pass        iftype!=None:Pass        Else :            Pass        Print 'This is exit'    def __del__(self):Print 'This is del'@staticmethoddefStaticmethod ():Print 'This is Staticmethod'Text_sort.staticmethod () test1=Text_sort () with test1 as D:deld Result: this isStaticmethodthis isInitthis isEnterthis isExitthis is del

Classes of exercises, including classes worth passing, etc.:

" "Listinfo included methods: 1 List element additions: Add_key (KeyName) [KeyName: String or integer type]2 list element value: Get_key (num) [num: integer type]3 list merge: Update_list ( Lists) [list: Type]4 deletes and returns the last element: Del_key ()" "classListinfo (object):def __init__(self,*lists):#do not use magic parameter Self.args=args processing        #how to handle using magic parameters (direct write parameters without parentheses)self.args=[]         forXinchlists:self.args.append (x)defAdd_key (self,keyname):ifIsinstance (KeyName, str)orisinstance (keyname, int): Self.args.append (KeyName)returnTrueElse:            returnFalsedefGet_key (self,num): Result=[]        ifisinstance (num, int): forXinchSelf.args:ifLen (Result) <= num-1: Result.append (x)Else:                    Pass        returnresultdefupdate_list (self,list_in):ifisinstance (list_in, list): Self.args.extend (list_in)returnSelf.argsElse:            return 'Not list type'Self.argsdefDel_key (self):returnSelf.args.pop ()defGet_all (self):returnself.argslisttest=listinfo (4,222,111,33,4545,'SSS','332') Listtest.add_key (9999)PrintListtest.get_key (3)PrintListtest.update_list ([1])PrintListtest.del_key () results [4, 222, 111][4, 222, 111, 33, 4545,'SSS','332', 9999, 1]1

Python's advanced functions map,reduce and filter: They all work on a Literable object. Lambda is similar to anonymous functions, and in some places it can be interchanged with list generation.

foo=[12,24,36,48,11,33,55,77]map (Lambda x:x*2+5, foo) #将第一个函数分别作用于后面的literable对象, and returns a list result: [+, +, 101, 159]filter (Lambda x:x%2==0,foo) # The first function is used for the subsequent Literable object, which matches the result of the returned list result: [x, X,]reduce (Lambda x,y:x+y,foo) # The Literable Element 22 operation, and the result after each operation as the first parameter of the next operation result:296
[x for x in foo if x%2 = = 0] #结果与filter一样

Python Learning notes functions and classes

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.