Gnumed.pycommon.gmBorg

Package Gnumed :: Package pycommon :: Module gmBorg |
[frames] | no frames]

# Source Code for Module Gnumed.pycommon.gmBorg

     1  #===================================================
     2  # Thanks to Python Patterns !
     3  # ---------------------------
     4  __author__ = "Karsten.Hilbert@gmx.net"
     5  __license__ = "GPL v2 or later"
     6
     7  #===================================================
     8 -class cBorg(object):
     9          """A generic Borg mixin for new-style classes.
    10
    11          - mixin this class with your class' ancestors to borg it
    12
    13          - there may be many _instances_ of this - PER CHILD CLASS - but they all share _state_
    14          """
    15          _instances = {}
    16
    17 -        def __new__(cls, *args, **kargs):
    18                  # look up subclass instance cache
    19                  if cBorg._instances.get(cls) is None:
    20                          #cBorg._instances[cls] = object.__new__(cls, *args, **kargs)
    21                          cBorg._instances[cls] = object.__new__(cls)
    22                  return cBorg._instances[cls]
    23
    24  #===================================================
    25  if __name__ == '__main__':
    26
    27          import sys
    28
    29          if len(sys.argv) < 2:
    30                  sys.exit()
    31
    32          if sys.argv[1] != 'test':
    33                  sys.exit()
    34
    35
    36 -        class A(cBorg):
    37                  pass
    38
    39 -        class B(cBorg):
    40                  pass
    41
    42 -        class C(cBorg):
    43 -                def __init__(self, val='default'):
    44                          self.x = val
    45
    46          print("testing new-style classes borg")
    47          a1 = A()
    48          a2 = A()
    49          a1.a = 5
    50          print(a1.a, "==", a2.a)
    51          a3 = A()
    52          print(a1.a, "==", a2.a, "==", a3.a)
    53          b1 = B()
    54          b1.a = 10
    55          print(b1.a)
    56          print(a1.a)
    57          b2 = B()
    58          print(b2.a)
    59
    60          c1 = C(val = 'non-default')
    61          print(c1.x)
    62          c2 = C(val = 'non-default 2')
    63          print(c2.x)
    64          c3 = C()
    65          print(c3.x)
    66
    67  #===================================================
    68