"""无参类常量与显式适配器区分;不假设JSON自动注入。""" import inspect import json from math import isfinite class SignalEngine: WINDOW = 3 THRESHOLD = 0.0 def generate(self, closes): if type(self.WINDOW) is not int or self.WINDOW < 2: raise ValueError('window必须为至少2的整数') if not isfinite(self.THRESHOLD) or self.THRESHOLD < 0: raise ValueError('threshold必须是有限非负数') return [int(i >= self.WINDOW - 1 and close > sum(closes[i-self.WINDOW+1:i+1]) / self.WINDOW * (1+self.THRESHOLD)) for i, close in enumerate(closes)] def reference_style_load(config): return SignalEngine() # 此最小路径没有策略参数注入;config只作为反例输入 def explicit_adapter(spec): if set(spec) != {'window', 'threshold'}: raise ValueError('策略参数字段不符') cls = type('ConfiguredEngine', (SignalEngine,), {'WINDOW': spec['window'], 'THRESHOLD': spec['threshold']}) return cls() closes = [10, 20, 18] base = reference_style_load({}) ignored = reference_style_load({'window': 2}) window_two = explicit_adapter({'window': 2, 'threshold': 0}) threshold_high = explicit_adapter({'window': 3, 'threshold': .2}) assert str(inspect.signature(SignalEngine)) == '()' assert base.generate(closes) == ignored.generate(closes) == [0, 0, 1] assert ignored.WINDOW == 3 assert window_two.generate(closes) == [0, 1, 0] assert threshold_high.generate(closes) == [0, 0, 0] try: explicit_adapter({'window': 2, 'threshold': 0, 'commission': 1}) except ValueError: pass else: raise AssertionError('引擎费用不能静默成为策略参数') for spec in [{'window': 0, 'threshold': 0}, {'window': True, 'threshold': 0}, {'window': 3, 'threshold': float('nan')}]: try: explicit_adapter(spec).generate(closes) except ValueError: pass else: raise AssertionError('无效参数必须拒绝') print(json.dumps({'closes': closes, 'default': base.generate(closes), 'ignored_json_window': {'requested': 2, 'effective': ignored.WINDOW, 'signals': ignored.generate(closes)}, 'explicit_window_2': window_two.generate(closes), 'explicit_threshold_point_2': threshold_high.generate(closes), 'scope': 'explicit adapter is authored here, not a verified product feature'}))