How to add property to a class dynamically?

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

    Here is the simple example to create property object programmatically.

    #!/usr/bin/python3
    
    class Counter:
        def __init__(self):
            cls = self.__class__
            self._count = 0
            cls.count = self.count_ref()
    
        def count_get(self):
            print(f'count_get: {self._count}')
            return self._count
    
        def count_set(self, value):
            self._count = value
            print(f'count_set: {self._count}')
    
        def count_del(self):
            print(f'count_del: {self._count}')
    
        def count_ref(self):
            cls = self.__class__
            return property(fget=cls.count_get, fset=cls.count_set, fdel=cls.count_del)
    
    counter = Counter()
    
    counter.count
    for i in range(5):
        counter.count = i
    del counter.count
    
    '''
    output
    ======
    count_get: 0
    count_set: 0
    count_set: 1
    count_set: 2
    count_set: 3
    count_set: 4
    count_del: 4
    '''
    

提交回复
热议问题