简体   繁体   English

如何在Python中将对类/函数的调用转换为字符串?

[英]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. 我已经使用Stack Exchange来查找我的许多问题的答案,而不需要问(这是一个很棒的社区),但我似乎无法在任何地方找到答案。 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. 我正在使用open()来访问文本文件,并使用eval()在加载信息时从字符串中更改它。 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)). 我想保留randint(1,10)部分,因为我想重用该函数,但我可能会根据用户选择将值更改为其他值(例如将self.lucky_number = randint(1,10)更改为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. 我知道我可以将它改为self.lucky_number = randint(1,var),然后保存var的值,但它让我想知道我正在尝试的方式是否可行。

Thanks in advance for any assistance. 在此先感谢您的任何帮助。 I am using Python 3.5. 我使用的是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. 编辑:为了澄清我想在文本文件中存储实际函数,即randint(1,10),而不是函数的值。

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. 编辑2:我将接受这个回答,因为我找到了一种方法来做我需要的,但这不是直接的方式。

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. 现在运行该函数的另一个类变量现在有eval()并调用我创建的新类变量。 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. 我可以将self.temp更改为我需要的任何变量(格式正确)并且代码可以工作。 If anyone can think of a direct way please let me know. 如果有人能想到直接的方式,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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