How to add property to a class dynamically?

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

    For those coming from search engines, here are the two things I was looking for when talking about dynamic properties:

    class Foo:
        def __init__(self):
            # we can dynamically have access to the properties dict using __dict__
            self.__dict__['foo'] = 'bar'
    
    assert Foo().foo == 'bar'
    
    
    # or we can use __getattr__ and __setattr__ to execute code on set/get
    class Bar:
        def __init__(self):
            self._data = {}
        def __getattr__(self, key):
            return self._data[key]
        def __setattr__(self, key, value):
            self._data[key] = value
    
    bar = Bar()
    bar.foo = 'bar'
    assert bar.foo == 'bar'
    

    __dict__ is good if you want to put dynamically created properties. __getattr__ is good to only do something when the value is needed, like query a database. The set/get combo is good to simplify the access to data stored in the class (like in the example above).

    If you only want one dynamic property, have a look at the property() built-in function.

提交回复
热议问题