【发布时间】:2018-07-11 13:59:58
【问题描述】:
我在 python 3.6.5 中使用 Flask-SQLAlchemy,并且 - 到目前为止 - 无法通过调用 __init__() 来扩展模型。我的代码如下所示:
'''
file: models.py
'''
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Network(db.Model):
__tablename__ = 'network'
id = db.Column(db.Integer, primary_key=True)
baud_rate = db.Column(db.Integer)
def __init__(**kwargs):
super(Network, self).__init__(**kwargs) # see note
尝试实例化网络对象会导致错误:
>>> n = Network(baud_rate=300)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: __init__() takes 0 positional arguments but 1 was given
这有点令人惊讶,因为我使用的是the recipe given in the Flask-SQLAlchemy documentation:
如果您出于任何原因决定重写构造函数,请确保 继续接受 **kwargs 并用这些调用超级构造函数 **kwargs 以保留此行为:
class Foo(db.Model): # ... def __init__(**kwargs): super(Foo, self).__init__(**kwargs) # do custom stuff
由于我使用的是 python 3.6,我想也许我应该将调用升级到 super(),如下所示:
def __init__(**kwargs):
super().__init__(**kwargs)
...但这没有任何区别。
【问题讨论】:
标签: python python-3.x flask flask-sqlalchemy