Check the following example working code of our implementation of nested classes with mixed staticmethods.
import time
class A:
def __init__(self):
time.sleep(0.1)
def a1(self):
print 'a1'
@staticmethod
def a2():
print 'a2'
class B:
@staticmethod
def b2():
A.a2() #fine.
A().a1() #very bad solution, computation cost is high !!!
@staticmethod
def x():
t = time.clock()
for i in xrange(100):
A.B.b2()
print 'elapsed: %0.1fs'%(time.clock()-t)
to use as:
A.B.x()
The above works but as you may notice for line A().a1() in which we have tried to get access to a non-static method a1 from container class A the computation cost is too high. We emphasized this point by having sleep in A initialization. So you get the point, it can be any time consuming initialization which is necessary in our work, for example. So we don't believe instantiating class A in the mentioned line is a good choice. How to not to instantiate A in the above but having the job done as exactly as above. The question above has bot been answered anywhere although related ones include this and that.
EDIT:
We are not interested in recommendations such as why use it etc. The question of our interest as clearly pointed out above is how to improve just this line
A().a1()
that's all.
Solved in the following way based on advice given by Martijn Pieters. We accepted the answer due to showing the way to solve.
class B:
@staticmethod
def b2(Ai):
A.a2() #fine.
if Ai is None: Ai = A()
Ai.a1() #now is fine.
@staticmethod
def x():
t = time.clock()
Ai = A()
for i in xrange(100):
A.B.b2(Ai=Ai)
print 'elapsed: %0.1fs'%(time.clock()-t)
Thank You.
Awithout instanciatingA?Amillion times just to access to methoda1. There should somehow to do this only with one instance.Atakes long to initialize then do it only once, caching the instances. You can do this with a very simple__new__method.