Understand Python Function [closed]

2024/10/9 5:12:53

I'm learning Python and wanted to see if anyone could help break down and understand what this function does step by step?

def label(self, index, *args): """ Label each axes one at a time args are of the form <label 1>,...,<label n> APIPARAM: chxl """ self.data['labels'].append( str('%s:|%s'%(index, '|'.join(map(str,args)) )).replace('None','') ) return self.parent 
Answer

It's a good idea to change the formatting, before trying to understand what it does:

def label(self, index, *args): """ Label each axes one at a time args are of the form <label 1>,...,<label n> APIPARAM: chxl """ self.data['labels'].append( str( '%s:|%s' % \ ( index, '|'.join( map( str,args ) ) ) ).replace( 'None', '' ) ) return self.parent 

So:

it appends something to self.data[ 'labels' ] list. We know this because append() is a method of list object.

This something is a string such that:

  • string is of the form xxx:|yyy
  • xxx is replaced with the value of argument index
  • yyy is replaced with all the other arguments converted to strings (map(str,args)) and joined with | character (join(...)) so resulting in something like 'a|b|None|c'
  • every occurence of None in the string above is replaced with an empty string and this is appended to the list

EDIT:

As @abarnert pointed out it might be good to explain what does *args mean and why later on it's used as args, so here it goes.

*args (which is an asterisk + an arbitrary name) means "any number of anonymous arguments available further in args list". One can also use **kwargs - note two asterisk which is used for accepting keyworded arguments, i.e. ones passed to the function in the form of foo = bar where foo is the name of the argument and bar is its value rather than just bar.

As said above args and kwargs are arbitrary, one could just as well use *potatoes or **potatoes but using args and kwargs is a convention in Python (sometimes people also use **kw instead of **kwargs, but the meaning is the same - any number of anonymous and any number of keyworded arguments respectively).

Both are used if the number of arguments which the function/method should accept is not known beforehand - consider for a example a function which processes names of the party guests, one may not know how many there may be, so defining a following function makes sense:

def add_party_quests( *quests ):for guest in quests:do_some_processing( guest )

Then both calls below are valid:

add_party_guests( 'John' )
add_party_guests( 'Beth', 'Tim', 'Fred' )

This is also explained in this SO post: https://stackoverflow.com/a/287101/680238

https://en.xdnf.cn/q/118625.html

Related Q&A

how to download linkedin (save as pdf option) using python

Image what i want to download.Image is of LinkedIn profile page of my friend i want to click on that save-as-pdf option for many users.can that be downloaded using python code? for different users? o…

My tkinter entry box is printing .!entry instead of what is entered

from tkinter import * def _name_():businessname=entry_bnprint(businessname) edit_bar=Tk() name=Label(edit_bar,text="Name:").grid(row=0) entry_bn=Entry(edit_bar) entry_bn.grid(row=0,column=1) …

How to get an average from a row then make a list out of it [duplicate]

This question already has answers here:Reading a CSV file, calculating averages and printing said averages(2 answers)Closed 6 years ago.If I have a csv data that gives two row values of:years grades 20…

Beautiful soup: Extract everything between two tags when these tags have different ids

Beautiful soup: Extract everything between two tags I have seen a question through the above link where we are getting the information between two tags. Whereas I need to get the information between th…

exceptions.RuntimeError - Object has no attribute errno [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 6 years ago.Improve…

How can I translate this python function to c++?

I am trying to translate a python function to c++ without success. Can someone help me? The python function receives as input a string S and 2 integers (fragment_size and jump). The aim of this functi…

Reverse PDF imposition

I have an imposed document: there are 4 n A4 pages on the n sheets. I put them into a roller image scanner and receive one 2 n paged PDF document (A3).If, say, n = 3, then Ive got the following seque…

Python: How to run flask mysqldb on Windows machine?

Ive installed the flask-mysqldb module with pip package management system on my Windows machine and I dont know how to run it.I have tried to add the path to the MySQLdb in System properties and still …

Match a pattern and save to variable using python

I have an output file containing thousands of lines of information. Every so often I find in the output file information of the following formInput Orientation: ... content ... Distance matrix (angstro…

Sharing a Queue instance between different modules

I am new to Python and I would like to create what is a global static variable, my thread-safe and process-safe queue, between threads/processes created in different modules. I read from the doc that t…