python - Automatically create (and keep) an object when accessed -


i this:

class a:     def hello(): print "hello"  # not want explicitly setup a: = a()  # = a() -> want happen automatically when access # first try this: def a():     return a()  # also, not want call function a(): must object # , must stay alive , initialized a.hello() # created, object of class a.hello() # not want second instantiation 

how can implement this? properties? cached-properties? classes: module-level object.

def lazyinit(cls):      class p(object):         def __init__(self, *args, **kws):             self._init = lambda: cls(*args, **kws)                         self._obj  = none          def __getattr__(self, k):             if not self._obj:                 self._obj = self._init()             return getattr(self._obj, k)      return p 

example:

@lazyinit class a(object):     def __init__(self, a, b):         print("initializing...")         self.x = + b + 2      def foo(self):         return self.x  x = a(39, 1) print x print x.foo() print x.foo() 

Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -