简体   繁体   中英

How do you convert a call to a class/function to a string in Python?

I am new to programming and self taught. I have used Stack Exchange to find answers to many of my questions without ever needing to ask (it is a great community), but I cannot seem to find the answer to this anywhere. I apologize if this is a duplicate.

I am trying to assign a method to a variable, but I want to save it to a text file for access later. I am using open() to access the text file and eval() to change it from a string when loading the information. I just cannot figure out how to do the opposite.

from random import randint

class Example (object):
    def __init__(self):
        self.name = ""
        self.lucky_number = ""

    def create_person(self):
        self.name = input("What is your name?")
        self.lucky_number = randint(1,10)
        save_person = [self.name, self.lucky_number]
        with open("example.txt", "w") as f:
            for i in save_person:
                f.write(i + '\n')

    def load_person(self):
        with open("example.txt", 'r') as f:
            person_list = f.readlines()
        if len(person_list) <= 1:
            create_person()
        else:
            self.name = person_list[0].strip('\n')
            self.lucky_number = eval(person_list[1].strip('\n'))

person = Example()
person.load_person()

I want to keep the randint(1,10) part because I want to reuse the function, but I may change the value to something else later depending on user selection (such as changing self.lucky_number = randint(1,10) to self.lucky_number = randint(1,30)).

I know I can just change it to self.lucky_number = randint(1,var) and then save the value of var instead, but it made me wonder if the way I'm trying is possible.

Thanks in advance for any assistance. I am using Python 3.5.

Edit: For clarification I am looking to store the actual function, ie randint(1,10), in the text file, not the value of the function.

EDIT 2: I am going to close this as answered because I found a way to do what I needed, but it is not a direct way.

I was able to find a way to accomplish what I was looking for, but it is a roundabout way. I changed the call to the function into a string, then created a new class variable that calls the variable with the function string. The other class variable meant to run the function now has eval() around it and calls the new class variable I created. I save the new class variable instead.

from random import randint

# Now a string instead of a function call
prog = "randint(1,10)"

class Example (object):
    def __init__(self):
        self.name = ""
"""Added self.temp to grab the string from outer 
variable and will change self.temp to get the desired
functions as strings"""
        self.temp = prog
"""self.lucky_number grabs new class variable and
eval() turns it into callable function"""
        self.lucky_number = eval(self.temp)

    def create_person(self):
        self.name = input("What is your name?")
        self.temp = prog
        self.lucky_number = eval(self.temp)
""" Saves new class variable now and stores actual 
function, eg randint(1,10)"""
        save_person = [self.name, self.temp]
        with open("example.txt", "w") as f:
            for i in save_person:
                f.write(str(i) + '\n')

    def load_person(self):
        with open("example.txt", 'r') as f:
            person_list = f.readlines()
        if len(person_list) <= 1:
            self.create_person()
        else:
            self.name = person_list[0].strip('\n')
            self.temp = person_list[1].strip('\n')

person = Example()
person.load_person()

Its roundabout, but gets the job done. I can change self.temp to whatever variable (formatted properly) I need and the code will work. If anyone can think of a direct way please let me know.

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