0

I want to write to a text file the function text as it is passed to a variable:

myvariable = myClass(arg1, arg2, arg3, arg4, arg_n)

f = open("mytextfile.txt", "w")
f.write("here is my paremeters:"+ str(myvariable))
f.close()

in my printout text file, I get:

"here is my parameters:<somefunction.myClass instance at 0x7d54a5101b48>"

the desired output will be:

"here is my parameters: myClass(arg1, arg2, arg3, arg4, arg_n)"

I should use the myvariable because the arguments change from time to time, so I can't hardcode the function text as it is.

jacky
  • 524
  • 1
  • 5
  • 15

1 Answers1

0

Since you commented with a third-party library and this isn't your own class...

Not pretty, but it works.

def string_it(c):
    return """myClass({}, {}, {}, {}, {})""".format(
        c.arg1, c.arg2, c.arg3, c.arg4, c.argN
    )

f.write("here are my parameters: {}\n".format(string_it(myvariable)))

Or you can try to implement it on that variable.

(haven't tried myself, but it is just a function re-mapping)

myvariable.__str__ = lambda s: """myClass({}, {}, {}, {}, {})""".format(
        myvariable.arg1, myvariable.arg2, myvariable.arg3, myvariable.arg4, myvariable.argN
    )

And then str(myvariable) might work

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245