簡體   English   中英

當我使用的較新版本的庫使用不同的函數名稱時,如何解決硬編碼? -蟒蛇

[英]How to resolve the hardcoding when a newer version of the library i use uses a different function name? - python

當我使用的庫使用函數的其他名稱時,是否有更好的方法來解決對兼容代碼進行硬編碼的問題?

另外, 我無法更改庫代碼。 (因為在舊版本的代碼中,我正在使用的功能無處不在)。 該庫為BeautifulSoup 3和4。請參見http://www.crummy.com/software/BeautifulSoup/bs4/doc/中的“ Method Name部分

本來我有bs4代碼,但我的用戶有bs3,所以我必須將以下代碼放在各處:

try:
  from bs4 import BeautifulSoup as bs
except:
  from BeautifulSoup import BeautifulSoup as bs

page = '''<html>foo bar<p>blah blah black sheep</p> bar</html>'''

try:
  p = bs(page).find_all('p')
except: # Imagine i have to do this all over my code that uses `find_all` or `findAll`
  p = bs(page).findAll('p')

可能是您應該對bs進行猴子補丁處理:

try:
    from bs4 import BeautifulSoup as bs
except:
    from BeautifulSoup import BeautifulSoup as bs

bs.find_all = getattr(bs, 'find_all', False) or getattr(bs, 'findAll')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM