简体   繁体   中英

Python - Extract private variables from a function?

I have a function f2(a, b)

It is only ever called by a minimize algorithm which iterates the function for different values of a and b each time. I would like to store these iterations in excel for plotting.

Is it possible to extract these values (i only need to paste them all into excel or a text file) easily? Conventional return and print won't work within f2. Is there any way to extract the values a and b to a public list in the main body some other way?

The algorithm may iterate dozens or hundreds of times.

So far I have tried:

  • Print to console (can't paste this data into excel easily)

  • Write to file (csv) within f2, the csv file gets overwritten within the function each time though.

Append the values to a global list.

values = []
def f2(a,b):
    values.append((a,b))
    #todo: actual function logic goes here

Then you can look at values in the main scope once you're done iterating.

Write to file (csv) within f2, the csv file gets overwritten within the function each time though.

Not if you open the file in append mode:

with open("file.csv", "a") as myfile:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM