Home > Enterprise >  Convert string to class object and add custom function to it in Python
Convert string to class object and add custom function to it in Python

Time:09-17

I have a string path "path=D:/projects/file.ext". Is there a way to convert this string to class and add to it a method which will do something with file.ext? The file could be any type Does not matter. For example:

my_file="D:/projects/file.ext"
obj = StrToObj(my_file)
obj.do_something_with_file()

CodePudding user response:

I think you can follow this template:

class StrToObj:
    def __init__(self, name, ...):
        self.name = name
        ...
    def do_something_with_file(self, ...):
        ...

CodePudding user response:

This is an odd situation, but here is how I interpret your question:

# Define object
class obj:
     def __init__(self, file):
          self.file = file
# function to open file and pass it to a class
def strToObj(name):
     with open(name, "r") as f:
          obj_1 = obj(f)
     return obj_1
  • Related