classStudent(object):@propertydefscore(self):returnself._score@score.setterdefscore(self,value):ifnotisinstance(value,int):raiseValueError('score must be an integer!')ifvalue<0orvalue>100:raiseValueError('score must between 0 ~ 100!')self._score=value
defhi(name="yasoob"):print("now you are inside the hi() function")defgreet():return"now you are in the greet() function"defwelcome():return"now you are in the welcome() function"print(greet())print(welcome())print("now you are back in the hi() function")hi()#output:now you are inside the hi() function# now you are in the greet() function# now you are in the welcome() function# now you are back in the hi() function# 上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用。# 然后greet()和welcome()函数在hi()函数之外是不能访问的,比如:greet()#outputs: NameError: name 'greet' is not defined
defa_new_decorator(a_func):defwrapTheFunction():print("I am doing some boring work before executing a_func()")a_func()print("I am doing some boring work after executing a_func()")returnwrapTheFunctiondefa_function_requiring_decoration():print("I am the function which needs some decoration to remove my foul smell")a_function_requiring_decoration()#outputs: "I am the function which needs some decoration to remove my foul smell"a_function_requiring_decoration=a_new_decorator(a_function_requiring_decoration)#now a_function_requiring_decoration is wrapped by wrapTheFunction()a_function_requiring_decoration()#outputs:I am doing some boring work before executing a_func()# I am the function which needs some decoration to remove my foul smell# I am doing some boring work after executing a_func()
A simple way
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@a_new_decoratordefa_function_requiring_decoration():"""Hey you! Decorate me!"""print("I am the function which needs some decoration to ""remove my foul smell")a_function_requiring_decoration()#outputs: I am doing some boring work before executing a_func()# I am the function which needs some decoration to remove my foul smell# I am doing some boring work after executing a_func()#the @a_new_decorator is just a short way of saying:a_function_requiring_decoration=a_new_decorator(a_function_requiring_decoration)
decorator with parameters:
1
2
3
@decorator(params)deffunc_name():''' Function implementation'''
The above code is equivalent to
1
2
3
4
5
deffunc_name():''' Function implementation'''func_name=(decorator(params))(func_name)"""
example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fromfunctoolsimportwrapsdeflogit(func):@wraps(func)defwith_logging(*args,**kwargs):print(func.__name__+" was called")returnfunc(*args,**kwargs)returnwith_logging@logitdefaddition_func(x):"""Do some math."""returnx+xresult=addition_func(4)# Output: addition_func was called
1
2
3
4
5
6
7
defdecorator(func):defwrapper(*args,**kwargs):# Do something before function calledans=func(*args,**kwargs)# Do something after function calledreturnansreturnwrapper
defdecorator_func(x,y):defInner(func):defwrapper(*args,**kwargs):print("I like Geeksforgeeks")print("Summation of values - {}".format(x+y))func(*args,**kwargs)returnwrapperreturnInner# Not using decoratordefmy_fun(*args):foreleinargs:print(ele)# another way of using decoratorsdecorator_func(12,15)(my_fun)('Geeks','for','Geeks')
equal toggle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
defdecorator_func(x,y):defInner(func):defwrapper(*args,**kwargs):print("I like Geeksforgeeks")print("Summation of values - {}".format(x+y))func(*args,**kwargs)returnwrapperreturnInner@decorator_func(12,15)defmy_fun(*args):foreleinargs:print(ele)my_fun('Geeks','for','Geeks')
解决原函数的元信息 (name) 替换问题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fromfunctoolsimportwrapsdefdecorator(func):@wraps(func)defwrapper(*args,**kwargs):"""doc of wrapper"""print('123')returnfunc(*args,**kwargs)returnwrapper@decoratordefsay_hello():"""doc of say hello"""print('同学你好')print(say_hello.__name__)print(say_hello.__doc__)
Add and update an item to the dictionary by specifying the key
1
dict_object[key]=new_value
Use the setdefault() method. If the key specified as the first argument already exists, the existing item remains unchanged as the original, no matter what value is specified as the second argument.
Standard CPython's garbage collector has two components, the reference counting collector and the generational garbage collector, known as gc module.
The reference counting algorithm is incredibly efficient and straightforward, but it cannot detect reference cycles. That is why Python has a supplemental algorithm called generational cyclic GC. It deals with reference cycles only
generations
In order to limit the time each garbage collection takes, the GC uses a popular optimization: generations. The main idea behind this concept is the assumption that most objects have a very short lifespan and can thus be collected shortly after their creation. This has proven to be very close to the reality of many Python programs as many temporary objects are created and destroyed very fast. The older an object is the less likely it is that it will become unreachable.
To take advantage of this fact, all container objects are segregated into three spaces/generations. Every new object starts in the first generation (generation 0). The previous algorithm is executed only over the objects of a particular generation and if an object survives a collection of its generation it will be moved to the next one (generation 1), where it will be surveyed for collection less often. If the same object survives another GC round in this new generation (generation 1) it will be moved to the last generation (generation 2) where it will be surveyed the least often.
Generations are collected when the number of objects that they contain reaches some predefined threshold, which is unique for each generation and is lower the older the generations are. These thresholds can be examined using the gc.get_threshold function:
1
2
3
>>>importgc>>>gc.get_threshold()(700,10,10)
arbitrary number of arguments
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
defcheeseshop(kind,*arguments,**keywords):print("-- Do you have any",kind,"?")print("-- I'm sorry, we're all out of",kind)forarginarguments:print(arg)print("-"*40)forkwinkeywords:print(kw,":",keywords[kw])cheeseshop("Limburger","It's very runny, sir.","It's really very, VERY runny, sir.",shopkeeper="Michael Palin",client="John Cleese",sketch="Cheese Shop Sketch")
output:
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch
resource.getrusage(who) 此函数返回一个对象,该对象描述当前进程或其子进程所消耗的资源,由 who 参数。这个 who 参数应使用 RUSAGE_* 常量如下所述。
1
2
3
4
5
6
7
8
9
10
11
fromresourceimport*importtime# a non CPU-bound tasktime.sleep(3)print(getrusage(RUSAGE_SELF))# a CPU-bound taskforiinrange(10**8):_=1+1print(getrusage(RUSAGE_SELF))
importthreadingimporttimeimportrandomclasssubclass:# Initialising the shared resourcesdef__init__(self):self.x=[]# Add an item for the producerdefproduce_item(self,x_item):print("Producer adding an item to the list")self.x.append(x_item)# Consume an item for the consumerdefconsume_item(self):print("Consuming from the list")consumed_item=self.x[0]print("Consumed item: ",consumed_item)self.x.remove(consumed_item)defproducer(subclass_obj,condition_obj):# Selecting a random number from the 1 to 3r=random.randint(1,3)print("Random number selected was:",r)# Creting r number of items by the producerforiinrange(1,r):print("Producing an item, time it will take(seconds): "+str(i))time.sleep(i)print("Producer acquiring the lock")condition_obj.acquire()try:# Produce an itemsubclass_obj.produce_item(i)# Notify that an item has been producedcondition_obj.notify()finally:# Releasing the lock after producingcondition_obj.release()defconsumer(subclass_obj,condition_obj):condition_obj.acquire()whileTrue:try:# Consume the itemsubclass_obj.consume_item()except:print("No item to consume, list empty")print("Waiting for 10 seconds")# wait with a maximum timeout of 10 secvalue=condition_obj.wait(10)ifvalue:print("Item produced notified")continueelse:print("Waiting timeout")break# Releasig the lock after consumingcondition_obj.release()if__name__=='__main__':# Initialising a condition class objectcondition_obj=threading.Condition()# subclass objectsubclass_obj=subclass()# Producer threadpro=threading.Thread(target=producer,args=(subclass_obj,condition_obj,))pro.start()# consumer threadcon=threading.Thread(target=consumer,args=(subclass_obj,condition_obj,))con.start()pro.join()con.join()print("Producer Consumer code executed")
# print to stdoutlogging.basicConfig(level=logging.DEBUG)
1
2
3
4
5
6
importlogginglogging.basicConfig(filename='example.log',encoding='utf-8',level=logging.DEBUG)logging.debug('This message should go to the log file')logging.info('So should this')logging.warning('And this, too')logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
multiprocessing 是一个支持使用与 threading 模块类似的 API 来产生进程的包。 multiprocessing 包同时提供了本地和远程并发操作,通过使用子进程而非线程有效地绕过了 全局解释器锁。 因此,multiprocessing 模块允许程序员充分利用给定机器上的多个处理器。 它在 Unix 和 Windows 上均可运行。
multiprocessing 模块还引入了在 threading 模块中没有的API。一个主要的例子就是 Pool 对象,它提供了一种快捷的方法,赋予函数并行化处理一系列输入值的能力,可以将输入数据分配给不同进程处理(数据并行)。下面的例子演示了在模块中定义此类函数的常见做法,以便子进程可以成功导入该模块。这个数据并行的基本例子使用了 Pool ,
frommultiprocessingimportProcess,Queuedeff(q):q.put([42,None,'hello'])if__name__=='__main__':q=Queue()p=Process(target=f,args=(q,))p.start()print(q.get())# prints "[42, None, 'hello']"p.join()
管道
1
2
3
4
5
6
7
8
9
10
11
12
frommultiprocessingimportProcess,Pipedeff(conn):conn.send([42,None,'hello'])conn.close()if__name__=='__main__':parent_conn,child_conn=Pipe()p=Process(target=f,args=(child_conn,))p.start()print(parent_conn.recv())# prints "[42, None, 'hello']"p.join()
frommultiprocessingimportProcess,current_process,parent_processimportosdefinfo(title):cur_process=current_process()print(cur_process)parent=parent_process()print(parent)if(parent==None):print("this is main process")deff(name):info('function f')print('hello',name)if__name__=='__main__':info('main line')p=Process(target=f,args=('bob',))p.start()
importargparseparser=argparse.ArgumentParser(description='manual to this script')parser.add_argument('--gpus',type=str,default=None)parser.add_argument('--batch-size',type=int,default=32)args=parser.parse_args()printargs.gpusprintargs.batch_size
fromopenpyxlimportload_workbookwb=load_workbook("demo.xlsx")# Sheet is the SheetName where the data has to be enteredsheet=wb["Sheet"]# Enter into 1st row and Ath columnsheet['A1']='Software Testing Help'# Similarly you can enter in the below shown fashionsheet.cell(row=2,column=1).value='OpenPyxl Tutorial'sheet['B1']=10sheet.cell(row=2,column=2).value=13.4wb.save("demo.xlsx")
There are 2 ways to enter the data in the Excel file. These are as follows:
Directly use columnrow combination. Example [A1], where A is the column and 1 is the row.
Use the row and column numbers. Example row=4, column=2
Add Sheets To The Excel File
1
2
3
sheetname="Day2 Result "+now.strftime("%d.%m.%Y")#Add new sheet using the index and title fieldswb.create_sheet(index=1,title=sheetname)
create_sheet(title=None, index=None)
Create a worksheet (at an optional index).
Parameters:
title (str): optional title of the sheet.
index (int): optional position at which the sheet will be inserted.
Appending Multiple Values Into Sheet
append(iterable)
Where iterable is a list of values or single value.
If it’s a list, all the values are added in order, starting from the first column.
If it’s one value, then the values are assigned to the columns indicated by the keys (numbers or letters).
1
2
3
4
5
6
7
8
9
10
11
12
fromopenpyxlimportload_workbookwb=load_workbook("demo.xlsx")#Mention the sheet where the data can be entered,sheet=wb["Day2 Result 27.07.2020"]# Assign multiple values to datadata=[('Emp Id','Emp Name','Designation'),(1,'XYZ','Manager'),(2,'ABC','Consultant')]#Append all rowsforiindata:sheet.append(i)wb.save("demo.xlsx")
Delete A Sheet From Excel Workbook
you can use wb.remove(sheetname) or del wb[sheetname]
1
2
3
4
5
6
7
8
9
10
importopenpyxlwb=openpyxl.load_workbook("DeleteSheet.xlsx")print("The names of work sheets before deleting")print(wb.sheetnames)sheetDelete=wb["Sheet2"]wb.remove(sheetDelete)#Sheet2 will be deleted#del wb[sheetDelete] #Alternatively you can use del cmdprint("The names of work sheets after deleting")print(wb.sheetnames)wb.save("DeleteSheet.xlsx")
Reading Data From The Excel File
directly use columnrow combination. Example [A1] or, use the row and column numbers. Example row=4, column=2.
sheet.cell().value command will help us retrieve the value from the specified cell.
1
2
3
4
5
6
7
fromopenpyxlimportload_workbookwb=load_workbook("demo.xlsx")sheet=wb.activedataAtA1=sheet['A1']dataAtA2=sheet.cell(row=2,column=1)print("Data at A1:",dataAtA1.value)print("Data at A2:",dataAtA2.value)
Reading All Values In The File
max_row-This gives the maximum row index containing data (1-based)
max_column – The maximum column index containing data (1-based)
fromopenpyxlimportload_workbookwb=load_workbook("demo.xlsx")sheet=wb["Day2 Result 27.07.2020"]row_count=sheet.max_rowcolumn_count=sheet.max_columnforiinrange(1,row_count+1):forjinrange(1,column_count+1):data=sheet.cell(row=i,column=j).valueprint(data,end=' ')print('\n')
Getting Column Letter
get_column_letter this converts a column index into a column letter. Example 3 to C.
Inserting and deleting rows and columns, moving ranges of cells