Referring to class names through strings?

后端 未结 5 1065
面向向阳花
面向向阳花 2021-01-16 17:32

I need to parse some text file, create objects for various entities encountered in the text, and put them in some data structure (e.g., a list) for further processing. Examp

5条回答
  •  一向
    一向 (楼主)
    2021-01-16 18:20

    Technically, what you're asking for (or at least the way everyone is interpreting it) just isn't very good practice, especially if you might be taking input from an untrusted source (remember, any source other than yourself should generally be considered untrusted!). You should whitelist these things explicitly, because someone might trigger the execution of a function or creation of an object you didn't intend with properties you really don't want...

    What you can do instead is something like this (this is of course wildly incomplete, but should give you the general idea):

    class Laptop(object):
        pass
    class Desktop(object):
        pass
    
    possible_classes = {
        "laptop": Laptop,
        "desktop": Desktop,
    }
    
    new_object = possible_classes[identifier_string](propA, propB, propC, ...)
    

    Then just add the mapping for each new kind of object to the possible_classes dict.

提交回复
热议问题