How to add property to a class dynamically?

前端 未结 24 1895
梦毁少年i
梦毁少年i 2020-11-22 12:44

The goal is to create a mock class which behaves like a db resultset.

So for example, if a database query returns, using a dict expression, {\'ab\':100, \'cd\'

24条回答
  •  抹茶落季
    2020-11-22 13:31

    I recently ran into a similar problem, the solution that I came up with uses __getattr__ and __setattr__ for the properties that I want it to handle, everything else gets passed on to the originals.

    class C(object):
        def __init__(self, properties):
            self.existing = "Still Here"
            self.properties = properties
    
        def __getattr__(self, name):
            if "properties" in self.__dict__ and name in self.properties:
                return self.properties[name] # Or call a function, etc
            return self.__dict__[name]
    
        def __setattr__(self, name, value):
            if "properties" in self.__dict__ and name in self.properties:
                self.properties[name] = value
            else:
                self.__dict__[name] = value
    
    if __name__ == "__main__":
        my_properties = {'a':1, 'b':2, 'c':3}
        c = C(my_properties)
        assert c.a == 1
        assert c.existing == "Still Here"
        c.b = 10
        assert c.properties['b'] == 10
    

提交回复
热议问题