How to add property to a class dynamically?

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

    You don't need to use a property for that. Just override __setattr__ to make them read only.

    class C(object):
        def __init__(self, keys, values):
            for (key, value) in zip(keys, values):
                self.__dict__[key] = value
    
        def __setattr__(self, name, value):
            raise Exception("It is read only!")
    

    Tada.

    >>> c = C('abc', [1,2,3])
    >>> c.a
    1
    >>> c.b
    2
    >>> c.c
    3
    >>> c.d
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'C' object has no attribute 'd'
    >>> c.d = 42
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 6, in __setattr__
    Exception: It is read only!
    >>> c.a = 'blah'
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 6, in __setattr__
    Exception: It is read only!
    

提交回复
热议问题