Suppose we want to create a "lazy" data attributes ( "instance variables" in Smalltalk, or "data members" in C++) in a Python Class. We may required to use getattr to customize attribute access.
Here is a example
class MyData(object): def __getattr__(self, attr): if attr == "pool" and attr not in self.__dict__: self.__dict__[attr] = ThreadPool(10) # lazy initialize here return self.__dict__[attr]
We may create a new instance using d = MyData()
, and once we call d.pool
, it will initialize a ThreadPool
at this moment.
1 Comment
rainbow · March 24, 2022 at 07:12
Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.