繁体   English   中英

在Flask-SQLAlchemy中添加__init __()方法

[英]Adding __init__() method in 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

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

>>> 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

这有点令人惊讶,因为我正在使用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)

......但这没有任何区别。

听起来像doc忘记在__init__提到self属性(在5月接受了pull请求 ):

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM