是否有可能以某种方式访问方法的变量或属性?
在Django中(但问题可能不在于Django):
class Product(models.Model):
...
STATISTIC = ['get_last_average_price',]
def statistic(self):
""" returns a list of methods with names in list STATISTIC """
lst = []
for method_str in Product.STATISTIC:
method = getattr(self, method_str)
lst.append(method)
return lst
def get_last_average_price(self):
self.get_last_average_price.label = 'Last AVG price'
self.get_last_average_price.xml_tag = '<last_average_price>'
self.get_last_average_price.xml_close_tag = '</last_average_price>'
prices = [x.get_last_scan().price for x in self.get_occurences() if x.get_last_scan() and x.get_last_scan().price]
return round(decimal.Decimal(sum(prices)/len(prices)),2) if prices else None
现在我想生成一个XML(方法为get_last_average_price
的迭代:
{{ method.xml_tag }}{{ method }}{{ method.xml_close_tag }}
应该产生:
<last_average_price>1548.48</last_average_price>
价格({{ method }}
)正常运作。问题出在标签上。
它返回错误:
异常值:'instancemethod'对象没有属性'label'
<products>
{% for product in products %}
<product>
<code>{{ product.code }}</code>
<name>{{ product.name }}</name>
<statistics>
{% for method in product.statistic %}
{{ method.xml_tag }}{{ method }}{{ method.xml_close_tag }}
{% endfor %}
</statistics>
</product>
{% endfor %}
</products>
你知道该怎么做才能让它发挥作用吗?或者一些解决方法?
答案 0 :(得分:1)
问题就在这里:
def get_last_average_price(self):
self.get_last_average_price.label = 'Last AVG price'
这里self.get_last_average_price
引用了一个实例方法,你没有调用它。不幸的是,要调用它会将它编码为self.get_last_average_price()
,因为它会导致无限递归。我想说数据结构需要完全改变。
def get_last_average_price(self):
prices = [x.get_last_scan().price for x in self.get_occurences() if x.get_last_scan() and x.get_last_scan().price]
value = round(decimal.Decimal(sum(prices)/len(prices)),2) if prices else None
return {"label": 'Last AVG price', "xml_tag": 'last_average_price', 'value': value }
请注意,您确实不需要xml_close_tag。因为那时可以派生标签(注意我已经删除了&lt;和&gt;让它们在下一阶段被追加。
答案 1 :(得分:0)
为什么不返回完整的XML行?
def get_last_average_price(self):
return '<last_average_price>{}</last_average_price>'.format(value)
然后:
{% for method in product.statistic %}
{{ method }}
{% endfor %}