singleton ... again
Asaf Las
roegltd at gmail.com
Wed Feb 12 12:56:33 EST 2014
There is another one.
Once object passes through singletonizator
there wont be any other object than first one.
Then object constructor can freely be used in every place
of code.
Curious if there could be any impact and applicability
of this to builtin types.
p.s. learned today that object __init__ member function is bound
to its class :-)
class singletonizator(object):
def __new__(cls, *args, **kwargs):
def newnew(cls, *args, **kwargs):
print("in new new", cls)
return cls.__dict__['hidden_object']
def newinit(self, *args, **kwargv):
print("in new init", self)
pass
if not 'hidden_object' in args[0].__class__.__dict__:
setattr(args[0].__class__, 'hidden_object', args[0])
args[0].__class__.__new__ = newnew
args[0].__class__.__init__ = newinit
return args[0]
class SomeClass:
def __init__(self, num):
print("in original init", self)
self.mynum = num
first_object = singletonizator(SomeClass(1))
print(first_object, first_object.mynum)
second_object = singletonizator(SomeClass(2))
print(second_object, second_object.mynum)
third_one = SomeClass(3)
print(third_one, second_object.mynum)
exit()
in original init <__main__.SomeClass object at 0x0000000002F338D0>
<__main__.SomeClass object at 0x0000000002F338D0> 1
in new new <class '__main__.SomeClass'>
in new init <__main__.SomeClass object at 0x0000000002F338D0>
<__main__.SomeClass object at 0x0000000002F338D0> 1
in new new <class '__main__.SomeClass'>
in new init <__main__.SomeClass object at 0x0000000002F338D0>
<__main__.SomeClass object at 0x0000000002F338D0> 1
More information about the Python-list
mailing list