【问题标题】:Adding __init__() method in Flask-SQLAlchemy在 Flask-SQLAlchemy 中添加 __init__() 方法
【发布时间】: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


    【解决方案1】:

    听起来文档忘记在__init__ 中提及self 属性(A pull request 在5 月被接受):

    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)
    

    【讨论】:

    • 是的 - 成功了。不过,这并不完全符合我的预期!
    猜你喜欢
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多