-1

I want to know how the __new__ function of type works, how can it create a class using the attr parameters.

for Example:

class ModelMetaclass(type): 
    def __new__(cls, name, bases, attrs):
        return type.__new__(cls, name, bases, attrs)

class User(Model): 
    __metaclass__ = ModelMetaclass
    id = StringField(primary_key=True, ddl='varchar(50)')
    email = StringField(ddl='varchar(50)')
    password = StringField(ddl='varchar(50)')

class StringField(Field):
    def __init__(self, **kw):
        self.name = kw.get('name', None)
        self.primary_key = kw.get('primary_key', False)
        self.ddl= kw.get('ddl', '')

Then, you can use User class like this: u = User(id=10190, name='Michael', email='orm@db.org') print type(u.id)

So, how does the __new__ function translate StringField into str ?

second
  • 28,029
  • 7
  • 75
  • 76

1 Answers1

0

how does the __new__ function translate StringField into str ?

Short answer: it doesn't - at least not in the code snippet you posted. Also, the StringFields are class attributes, not instance attributes, so self.id is not necessarily User.id.

Now you didn't post all the relevant code (we'd need to see at least the full ModelMetaclass, the Model class and the Field class code) nor any mention of where this code comes from, so it's hard to tell exactly what happens here. I assume there's much to than what you posted here, and FWIW Field could be a descriptor, or the whole thing could work like Django's Model and ModelField (where the ModelField are used for the ORM part but the matching Model instance attributes are just plain instance attributes).

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118