Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

python - Convert a string to preexisting variable names

How do I convert a string to the variable name in Python?

For example, if the program contains a object named self.post that contains a variable named, I want to do something like:

somefunction("self.post.id") = |Value of self.post.id|
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note: do not use eval in any case where you are getting the name to look up from user entered input. For example, if this comes from a web page, there is nothing preventing anyone from entering:

__import__("os").system("Some nasty command like rm -rf /*")

as the argument. Better is to limit to well-defined lookup locations such as a dictionary or instance using getattr(). For example, to find the "post" value on self, use:

varname = "post"
value = getattr(self, varname)  # Gets self.post

Similarly to set it, use setattr():

value = setattr(self, varname, new_value)

To handle fully qualified names, like "post.id", you could use something like the below functions in place of getattr() / setattr().

def getattr_qualified(obj, name):
    for attr in name.split("."):
        obj = getattr(obj, attr)
    return obj

def setattr_qualified(obj, name, value):
    parts = name.split(".")
    for attr in parts[:-1]:
        obj = getattr(obj, attr)
    setattr(obj, parts[-1], value)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...