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

Question:

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()
Asked By: iRex

||

Answers:

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
Answered By: the_electro_bros

I think you can follow this template:

class StrToObj:
    def __init__(self, name, ...):
        self.name = name
        ...
    def do_something_with_file(self, ...):
        ...
Answered By: Scaro974
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.