I have this code:
class Singleton(type):
  def __call__(cls,*args,**kwargs):
    if cls.created is None :
      print('called')
      cls.created = super().__call__(*args,**kwargs)
      return cls.created
    else:
      return cls.created
  def __new__(cls,name,base,attr,**kwargs):
    return super().__new__(cls,name,base,attr,**kwargs)
class OnlyOne(metaclass=Singleton):
  created = None
  def __init__(self,val):
      self.val = val
class OnlyOneTwo(OnlyOne):
  pass
k = OnlyOne(1)
a = OnlyOneTwo(2)
print(a.val)
print(k.val)
print('a.created: {0} - b.created: {1}'.format(id(a.created),id(k.created)))
I'm new to Python 3 so I decided to do some little experiment and playing around Python's metaclasses.
Here, I attempted to make a metaclass that will strict a class to a single instance when set.
I'm not sure yet if this works but whenever I try to do:
k = OnlyOne(1)
a = OnlyOneTwo(2)
the output will be:
called
1
1
which means that OnlyOneTwo wasn't set but when I try to do:
a = OnlyOneTwo(2)
k = OnlyOne(1)
the output will be:
called
called
2
1
Can someone help me traceback? I'm somehow confused but here are my initial questions/thoughts:
- Does - OnlyOneTwo's- createdproperty the same as- OnlyOne's ? because I get different results through- id()depending on which one I defined first. It's different if it's- OnlyOneTwofirst but it's the same if it's- OnlyOnefirst.
- How come - createdis still- Noneif I will run- a = OnlyOneTwo(2) print(OnlyOne.created)?
 
     
    