Created
June 25, 2019 09:05
-
-
Save allenyang79/41ea1200fbe6daf22d70587f678f2c5d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyMeta(type): | |
def __new__(cls, name, bases, dct): | |
print "meta: creating %s %s" % (name, bases) | |
for pkls in bases: | |
for key, value in pkls.__dict__.items(): | |
if isinstance(value, Field): | |
pass | |
#print name,value | |
#setattr(kls, key, value) | |
kls = type.__new__(cls, name, bases, dct) | |
return kls | |
def meta_meth(cls): | |
print "MyMeta.meta_meth" | |
__repr__ = lambda c: c.__name__ | |
class Field(object): | |
def __init__(self, field): | |
self.field = field | |
def __set__(self, instance, val): | |
setattr(instance, self.field, val) | |
def __get__(self, instance, cls): | |
if instance: | |
return getattr(instance, self.field, None) | |
return self | |
class A(object): | |
__metaclass__ = MyMeta | |
name = Field('_name') | |
age = Field('_age') | |
address = None | |
def __init__(self): | |
super(A, self).__init__() | |
print "A init" | |
def meth(self): | |
print "A.meth" | |
class B(object): | |
__metaclass__ = MyMeta | |
def __init__(self): | |
super(B, self).__init__() | |
print "B init" | |
def meth(self): | |
print "B.meth" | |
class C(A, B): | |
__metaclass__ = MyMeta | |
def __init__(self): | |
super(C, self).__init__() | |
print "C init" | |
print A.name | |
print C.name |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
write __metaclass__ in class directly. | |
""" | |
class ActiveRecord(object): | |
class __metaclass__(type): | |
def __new__(meta_cls, meta_cls_name, bases, dct): | |
print('__metaclass__ __new__', meta_cls, meta_cls_name, bases, dct) | |
return type.__new__(meta_cls, meta_cls_name, bases, dct) | |
def __init__(cls, name, bases, dct): | |
print('__metaclass__ __init__', cls, name) | |
class Foo(ActiveRecord): | |
pass | |
if __name__ == '__main__': | |
print('go') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment