class Field(object):
def __get__(self, instance, owner):
print('__get__', self, instance, self.name)
return getattr(instance, self.name)
def __set__(self, instance, value):
print('__set__', self, instance, self.name, value)
setattr(instance, self.name, value)
class Meta(type):
def __new__(meta, name, bases, class_dict):
print('__new__', name, bases, class_dict)
for name, value in class_dict.items():
if isinstance(value, Field):
setattr(value, 'name', '_' + name)
return type.__new__(meta, name, bases, class_dict)
class Model(object, metaclass=Meta):
pass
class Record(Model):
a = Field()
b = Field()
r = Record()
r.a = 'Bob'
r.b = 1234
Item 25: Metaclass
Posted by Logan Chien