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.

Categories: Code

Yu

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

1 Comment

rainbow · March 24, 2022 at 07:12

Google Chrome 96.0.4664.110 Google Chrome 96.0.4664.110 Windows 10 x64 Edition Windows 10 x64 Edition

Ideals are like the stars: we never reach them, but like the mariners of the sea, we chart our course by them.

Leave a Reply to rainbow Cancel reply

Your email address will not be published.