在 Flask-SQLAlchemy 中添加 __init__() 方法

fea*_*ool 3 python flask python-3.x flask-sqlalchemy

我在 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
Run Code Online (Sandbox Code Playgroud)

尝试实例化 Network 对象会导致错误:

>>> 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
Run Code Online (Sandbox Code Playgroud)

这有点令人惊讶,因为我使用的是 Flask-SQLAlchemy 文档中给出的配方

如果您出于任何原因决定覆盖构造函数,请确保继续接受 **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)
Run Code Online (Sandbox Code Playgroud)

……但这没有任何区别。

PRM*_*reu 5

听起来文档忘记self__init__(A pull request was Accepted in May) 中提及该属性:

class Network(db.Model):
    __tablename__ = 'network'

    id = db.Column(db.Integer, primary_key=True)
    baud_rate = db.Column(db.Integer)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
Run Code Online (Sandbox Code Playgroud)