我如下定义一个特定的烧瓶表
class MyTable(Table):
def __init__(self, table_id, rows):
self.table_id = table_id
super().__init__(rows)
Code = Col('Code', column_html_attrs = {'class': 'apply-filter'})
现在,如果我尝试通过在Code
内移动__init__
属性来概括它,
def __init__(self, table_id, rows, key):
self.table_id = table_id
self.__dict__[key] = Col(key, column_html_attrs = {'class': 'apply-filter'})
super().__init__(rows)
出了点问题,不再显示。
我也尝试过使用self.Code = ...
(这不是我想要的,因为它没有被泛化),但是它也失败了。
即使我找到了一个可行的答案,我仍然对此并不完全满意。 为什么我的原始代码也不好?父类的构造函数没有看到在派生类的初始化中动态创建的字段吗?
答案 0 :(得分:0)
通过在Flask Table的github源代码中寻找__init__
,找到了relevant example。
就我而言,我可以做到
def __init__(self, table_id, rows, key):
super().__init__(rows)
self.table_id = table_id
self.add_column(key, Col(key, column_html_attrs = {'class': 'apply-filter'}))
变得更普遍的是
class MyTable(Table):
def __init__(self, table_id, rows, keys):
super().__init__(rows)
self.table_id = table_id
for k in keys:
self.add_column(k, Col(k, column_html_attrs = {'class': 'apply-filter'}))
父类的构造函数没有看到在派生类的初始化中动态创建的字段吗?
否,因为父类有一个元类,它想从__new__
中读取属性,而元类在不存在这些动态字段的导入时执行。
为此,您可以通过导入table.TableMeta
table
。
from flask_table import Table, Col, table
那你可以做
class MyTable(Table):
def __init__(self, table_id, rows, keys, filters):
dict = {}
for k in keys:
if k in filters:
dict[k] = Col(k, column_html_attrs = {'class': 'apply-filter'})
else:
dict[k] = Col(k)
metadict = table.TableMeta.__new__(table.TableMeta, 'MyTable', (Table,), dict).__dict__
self.__dict__.update(metadict)
super().__init__(rows)
self.table_id = table_id
上面的方法行之有效,但这只是概念性答案,以便深入了解正在发生的事情。
在现实世界中,您只需要仔细阅读github存储库的完整自述文件即可。有一段Dynamically Creating Tables,只需按照说明进行操作,就可以轻松找到create_table
,后面您可以发现add_column
。