【问题标题】:How to avoid magic string in class field_name in python, something like nameof() in c#如何避免 python 中的 field_name 类中的魔术字符串,类似于 c# 中的 nameof()
【发布时间】:2020-04-06 11:13:50
【问题描述】:

例如,在这个 python 代码中。

from scrapy.loader import ItemLoader
from myproject.items import Product

def parse(self, response):
    l = ItemLoader(item=Product(), response=response)
    l.add_xpath('name', '//div[@class="product_name"]')
    l.add_xpath('name', '//div[@class="product_title"]')
    l.add_xpath('price', '//p[@id="price"]')
    l.add_css('stock', 'p#stock]')
    l.add_value('last_updated', 'today') # you can also use literal values
    return l.load_item()

如何避免使用 'name', 'price' 作为字符串。 有什么方法可以使用,比如

 l.add_xpath(getname(Product.name), '//div[@class="product_title"]')
 l.add_xpath((getname(Product.price), '//p[@id="price"]')

谢谢

【问题讨论】:

  • 为什么?如果您打错字,Scrapy Item 实例将引发异常。这只是为了在 IDE 中获得自动完成支持,还是其他什么?

标签: python scrapy magic-string


【解决方案1】:

通过使用getattr 内置函数

 product = Product()
 l.add_xpath(getattr(product, 'name'), '//div[@class="product_title"]')

【讨论】:

  • 感谢您的回复,但您的解决方案,不要避免使用魔术字符串'name'
  • name 不是一个神奇的字符串,但是在第一篇文章中分享您的 Product 类,我会更新我的回答。
  • 再次感谢,也许我不清楚,但我的目标是如果重命名字段 product.name 会出现编译错误。为此,我需要避免使用“字符串”作为字段名称。在 c# 中可以使用 nameof() 但不知道如何在 python 中做到这一点
  • 您应该使用 docs.python.org/3/library/functions.html#property 并在 setter 中添加您想要的任何类型的逻辑,包括在新名称与旧名称不同时抛出错误。
猜你喜欢
  • 1970-01-01
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多