Reputation: 3977
I am learning Web Development in Flask. I am using SQLAlchemy. A typical database object is structured like so:
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
default = db.Column(db.Boolean, default=False, index=True)
permissions = db.Column(db.Integer)
users = db.relationship('User', backref='role', lazy='dynamic')
def __repr__(self):
return '<Role %r>' % self.name
My question is, are these all class variables or object variables? They are outside the __init__
so it would seem they are class variables, that seems odd though. Any pointers on this would be great! Thanks!
Upvotes: 5
Views: 2417
Reputation: 3490
The fields with type Column
in Role
are indeed class variables. But they would be replaced with InstrumentedAttribute
during Role construction, which occurred in declarative.aqi.DeclarativeMeta.__init__()
This is why we define Role inherited from Base
with metaclass declarative.aqi.DeclarativeMeta
(the return value of declarative_base())
The InstrumentedAttribute
is a data descriptor, which defined __get__
and __set__
applied to instance dictionary. As a result, we could use them to do operation through instance.
In the following example, r.name
is a data descriptor, r.name = 'hello'
is equivalent to Role.name.__set__(r, 'hello')
-> r.__dict__['name'] = 'hello'
r = Role()
r.name = 'hello'
Upvotes: 8