How to add property to a class dynamically?

前端 未结 24 2118
梦毁少年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:22

    Here is a solution that:

    • Allows specifying property names as strings, so they can come from some outside data source instead of all being listed in your program.
    • Adds the properties when the class is defined, instead of every time an object is created.

    After the class has been defined, you just do this to add a property to it dynamically:

    setattr(SomeClass, 'propertyName', property(getter, setter))
    

    Here is a complete example, tested in Python 3:

    #!/usr/bin/env python3
    
    class Foo():
      pass
    
    def get_x(self):
      return 3
    
    def set_x(self, value):
      print("set x on %s to %d" % (self, value))
    
    setattr(Foo, 'x', property(get_x, set_x))
    
    foo1 = Foo()
    foo1.x = 12
    print(foo1.x)
    

提交回复
热议问题