1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
""" Some mocking """
class struct: pass
class _name_scope(object):
def __init__(self, *a): self.a = a
def __enter__(self):
print("in _name_scope", self.a)
return self
def __exit__(self, *b):
print("out _name_scope", self.a)
return self
def _Variable(*a, **k):
print("Variable", a, k)
return a[0]
tf = struct() #py3 mocking
tf.name_scope = _name_scope
tf.Variable = _Variable
tf.int32 = None
class Meta_(type):
@classmethod # Py3 only ...
def __prepare__(metacls, name, bases):
#print("prepare", metacls, name, bases) #prepare <class '__main__.Meta_'> TestMeta ()
metacls.opened = tf.name_scope("TestMeta").__enter__()
return {}
def __new__(cls, name, bases, classdict):
# print("new", cls, name, bases, classdict)
# new <class '__main__.Meta_'> TestMeta () {'cm': <__main__._name_scope object at 0x101826710>, '__module__': '__main__', '__qualname__': 'TestMeta', 'cx': 0, '__init__': <function TestMeta.__init__ at 0x1018239d8>}
cls.opened.__exit__(None, None, None) # cls_ is Meta_
return type.__new__(cls, name, bases, dict(classdict))
class TestMeta(metaclass=Meta_):
cx = tf.Variable(0, trainable=False, dtype=tf.int32, name="cx")
def __init__(self):
self.x = tf.Variable(0, trainable=False, dtype=tf.int32, name="x")
def demo_meta():
t= TestMeta()
print(t.cx, t.x)
if __name__ == '__main__':
demo_meta() |
Partager