如何从字符串创建Python类?
因此,我尝试创建一个文件,其中包含一组对象,如下所示:如何从字符串创建Python类?,python,class,file-io,Python,Class,File Io,因此,我尝试创建一个文件,其中包含一组对象,如下所示: <class 'oPlayer.oPlayer'>,123,4,<class 'CommonObject.Wall'>,175,4,<class 'CommonObject.Wall'>,25,654,<class 'CommonObject.Wall'>,1,123,<class 'CommonObject.Wall'>,55,87 文件中的对象都有两个参数,x和y。所以我也不
<class 'oPlayer.oPlayer'>,123,4,<class 'CommonObject.Wall'>,175,4,<class 'CommonObject.Wall'>,25,654,<class 'CommonObject.Wall'>,1,123,<class 'CommonObject.Wall'>,55,87
文件中的对象都有两个参数,x和y。所以我也不知道这是怎么回事。我所做的是获取包含所有拆分字符串的列表(我显示了这些字符串,结果是正确的。没有\n),然后我在列表中循环(排序)以设置所有数据。我假设type
将返回对象,但它没有返回
非常感谢您对上述主题的任何帮助。请尝试以下方法:
:
这是一个完整的示例(将其放在名为getattrtest.py
的文件中):
使用Python2.7测试此文件来自何处?这些类是在哪里定义的?这是怎么回事?!你只是在找吗?试试内置类型函数,看看我的答案这里
type
不返回对象,因为你没有对象,只有字符串。你不能从一个写着
的字符串中神奇地重新生成一个对象及其所有相关属性和方法。每个文件/类都在同一个目录中。为什么不使用json、yaml或pickle等自动可解析的序列化格式呢?我尝试了你的解决方案,但看起来这个对象实际上并没有被创建。我试图调用其中一个对象的超类函数,但它不允许我调用。之后如何创建对象?(顺便说一句,谢谢你的回复。)@Paolo:我在我的答案中添加了一个完整的示例,它可以工作,包括对超类的函数调用。可能是oPlayer.oPlayer
或CommonObject.Wall
def loadRoom(self, fname):
# Get the list of stuff
openFile = open(fname, "r")
data = openFile.read().split(",")
openFile.close()
# Loop through the list to assign said stuff
for i in range(len(data) / 3):
# Create the object at the position
newObject = type(data[i * 3])
self.instances.append(newObject(int(data[i * 3 + 1]), int(data[i * 3 + 2])))
import importlib
...
for i in range(len(data) / 3):
# get object data
cls = data[i * 3]
x = int(data[i * 3 + 1])
y = int(data[i * 3 + 2])
# get module and class
module_name, class_name = cls.split(".")
somemodule = importlib.import_module(module_name)
# instantiate
obj = getattr(somemodule, class_name)(x, y)
self.instances.append(obj)
import importlib
class Test1(object):
def __init__(self, mx, my):
self.x = mx
self.y = my
def printit(self):
print type(self)
print self.x, self.y
class Test2(Test1):
def __init__(self, mx, my):
# changes x and y parameters...
self.y = mx
self.x = my
def main():
cls = 'getattrtest.Test2'
# get module and class
module_name, class_name = cls.split(".")
somemodule = importlib.import_module(module_name)
# instantiate
obj = getattr(somemodule, class_name)(5, 7)
obj.printit()
if __name__ == "__main__":
main()