考虑一个简单的外汇计算器应用程序的例子。我可以使用traitlets以下方法定义我的模型:from traitlets import HasTraits, Float, observe, Enumimport mathclass FXModel(HasTraits): domestic_qty = Float() foreign_qty = Float() fx_rate = Float(float('nan')) # in units of domestic_qty/foreign_qty lock = Enum(['domestic', 'foreign'], default_value='domestic') _calculating = Enum([None, 'domestic', 'foreign'], default_value=None) def calc_foreign(self): if not math.isnan(self.fx_rate): self._calculating = 'foreign' self.foreign_qty = self.domestic_qty / self.fx_rate self._calculating = None def calc_domestic(self): if not math.isnan(self.fx_rate): self._calculating = 'domestic' self.domestic_qty = self.foreign_qty * self.fx_rate self._calculating = None @observe('domestic_qty') def on_domestic(self, change): if self._calculating is None: self.calc_foreign() @observe('foreign_qty') def on_foreign(self, change): if self._calculating is None: self.calc_domestic() @observe('fx_rate') def on_fxrate(self, change): if self.lock == 'domestic': self.calc_foreign() else: self.calc_domestic()以及相应的简单的基于“打印”的视图:class FXView: def __init__(self, model): self.model = model def show(self): print(""" domestic_qty: {:.4g} foreign_qty: {:.4g} fx_rate: {:.4g} lock: {}""".format( self.model.domestic_qty, self.model.foreign_qty, self.model.fx_rate, self.model.lock ))这是它的工作原理:>> fx_model = FXModel(domestic_qty = 100., fx_rate = 200.)>> fx_view = FXView(fx_model)>> fx_view.show() domestic_qty: 100 foreign_qty: 0.5 fx_rate: 200 lock: domestic它看起来非常好:我的问题是;我怎样才能“绑定”我的模型和我的 ipyview 在一起?我有一些经验enaml可以通过运营商:=和朋友来实现。这样做的最佳方法是什么ipywidgets?
添加回答
举报
0/150
提交
取消