How to add property to a class dynamically?

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

    It seems you could solve this problem much more simply with a namedtuple, since you know the entire list of fields ahead of time.

    from collections import namedtuple
    
    Foo = namedtuple('Foo', ['bar', 'quux'])
    
    foo = Foo(bar=13, quux=74)
    print foo.bar, foo.quux
    
    foo2 = Foo()  # error
    

    If you absolutely need to write your own setter, you'll have to do the metaprogramming at the class level; property() doesn't work on instances.

提交回复
热议问题