How to add property to a class dynamically?

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

    To answer the main thrust of your question, you want a read-only attribute from a dict as an immutable datasource:

    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':200}, then I would to see

    >>> dummy.ab
    100
    

    I'll demonstrate how to use a namedtuple from the collections module to accomplish just this:

    import collections
    
    data = {'ab':100, 'cd':200}
    
    def maketuple(d):
        '''given a dict, return a namedtuple'''
        Tup = collections.namedtuple('TupName', d.keys()) # iterkeys in Python2
        return Tup(**d)
    
    dummy = maketuple(data)
    dummy.ab
    

    returns 100

提交回复
热议问题