How to create Python class from a string? -
so trying have file has bunch of object in looks this:
<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
(no newlines splitting purposes)
the file holds object name, x, , y coordinate. (basic info) i'm not 100% sure how create objects file. here have:
def loadroom(self, fname): # list of stuff openfile = open(fname, "r") data = openfile.read().split(",") openfile.close() # loop through list assign said stuff in range(len(data) / 3): # create object @ position newobject = type(data[i * 3]) self.instances.append(newobject(int(data[i * 3 + 1]), int(data[i * 3 + 2])))
the objects in file take 2 arguments, x , y. i'm confused on how work. did grab list split strings, (which displayed, came out correct. no \n's) loop through list (sort of) set data. assumed type
return object, doesn't.
any said topic appreciated.
try approach get python class object string:
import importlib ... in range(len(data) / 3): # object data cls = data[i * 3] x = int(data[i * 3 + 1]) y = int(data[i * 3 + 2]) # module , 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)
here complete sample (put in file named getattrtest.py
):
import importlib class test1(object): def __init__(self, mx, my): self.x = mx self.y = def printit(self): print type(self) print self.x, self.y class test2(test1): def __init__(self, mx, my): # changes x , y parameters... self.y = mx self.x = def main(): cls = 'getattrtest.test2' # module , 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()
tested python 2.7
Comments
Post a Comment