我有一個檔案myfunctions.py在mypythonlib目錄下
from requests_html importHTMLSession
import requests
def champs_info(champname:str, tier_str:int) 。
url = f "https://auntm.ai/champions/{champname}/tier/{tier_str}"。
session = HTMLSession()
r = session.get(url)
r.html.render(sleep=1, keep_page=True, scrolldown=1)
information = r.html.find("div.sc-hiSbYr.XqbgT")
sig = r.html.find('div.sc-fbNXWD.iFMyOV')
tier_access = information[0]
tier = tier_access.text
我想通過另一個檔案訪問變數tier - test_myfunctions.py。
但問題是我還必須給函式champs_info提供引數,以便它能夠相應地訪問URL。
from mypythonlib import myfunctions
def test_champs_info()。
return myfunctions.champs_info("abomination",6).tier
但在運行這段代碼時,我得到的錯誤是--
。
./tests/test_myfunctions.py::test_champs_info Failed: [undefined]AttributeError: 'NoneType' object沒有屬性'tier'。
def test_champs_info():
> return myfunctions.champs_info("abomination",6).tier
E AttributeError: 'NoneType' object沒有屬性'tier'。
tests/test_myfunctions.py:3: 屬性錯誤(AttributeError
有什么解決辦法嗎?為什么這段代碼不能訪問這個變數?
我寫了myfunctions.champs_info("abomination",6).tier,希望它能從champs_info函式中獲取tier變數,同時從myfunctions檔案中獲得所需的引數:(
uj5u.com熱心網友回復:
在myfunctions.champs_info()中添加一個return tier
并且在腳本test_myfunctions.py中洗掉.tier
uj5u.com熱心網友回復:
你可以通過以下方式訪問函式中的變數值:1)在函式中回傳數值,2)使用模塊中的全域變數,或者3)定義一個類。
如果只想訪問一個函式本地的單一變數,那么該函式應該回傳該值。類定義的一個好處是,你可以根據你需要訪問的變數定義盡可能多的變數。
1. 回傳值
def champs_info(champname: str, tier_str:int)。)
...
tier = tier_access.text
return tier
2.global
tier = None。
def champs_info(champname:str, tier_str:int) 。
global tier
...
tier = tier_access.text
Global tier vairable被訪問。
from mypythonlib import myfunctions
def test_champs_info()。
myfunctions.champs_info("abomination"/span>, 6)
return myfunctions.tier.
print(test_champs_info() )
3.類定義:
class Champ。
def __init__(self):
self.tier = None。
def champs_info(self, champname:str, tier_str:int) 。
...
self.tier = tier_access.text
test_functions.py可以以這種方式呼叫champs_info()。
from mypythonlib import myfunctions
def test_champs_info()。
info = myfunctions.Champ()
info.champs_info("abomination"/span>, 6)
return info.tier.
print(test_champs_info()
uj5u.com熱心網友回復:
你只需要從champs_info()函式中回傳tier
。就像這樣:
myfunctions.py
from requests_html importHTMLSession
import requests
def champs_info(champname:str, tier_str:int) 。
url = f "https://auntm.ai/champions/{champname}/tier/{tier_str}"。
session = HTMLSession()
r = session.get(url)
r.html.render(sleep=1, keep_page=True, scrolldown=1)
information = r.html.find("div.sc-hiSbYr.XqbgT")
sig = r.html.find('div.sc-fbNXWD.iFMyOV')
tier_access = information[0]
tier = tier_access.text
return tier # <---- Focus Here
test_myfunctions.py
import myfunctions
print(temp.champs_info("americachavez"/span>, 6)
就這樣吧。你就完成了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/326649.html
標籤:
上一篇:如何使用Jackson將未包裝的JSON欄位映射到包裝的物件?
下一篇:Java中將字串轉換為鍵值對
