[英]OOP Python converting list of strings into a list of ShoppingItem objects and assign the list into the self.items_list variable
[英]Converting OOP objects to text in Python
我仍然是 OOP 的菜鳥。
class ItemPrices:
def __init__(self, name=" ", exval=0, chval=0, curtype= " "):
self.name = name
self.exaltedValue = exval
self.chaosValue = chval
self.currType = curtype
def Incubator_Values(self):
response_API = requests.get("https://poe.ninja/api/data/itemoverview?league=Scourge&type=Incubator")
data = response_API.text
os.chdir(
r"C:\Users\emosc\PycharmProjects\GithubPushs\psychescape_price_fetcher\psychescape_price_fetcher\values")
parse_json = json.loads(data)
with open("incubators.txt", "w") as file:
file.write(" ")
j = 0
for i in parse_json["lines"]:
list = []
if (i["chaosValue"] > chaos_ex_ratio):
self.name = i["name"]
self.exaltedValue = i["exaltedValue"]
self.currType = "Exalted Orb"
print(self.name)
list.append(self)
j = j + 1
print("Current iteration> ", j)
else:
self.name = i["name"]
self.exaltedValue = i["chaosValue"]
self.currType = "Chaos Orb"
print(self.name)
list.append(self)
j = j + 1
print("Current iteration> ", j)
os.chdir(
r"C:\Users\emosc\PycharmProjects\GithubPushs\psychescape_price_fetcher\psychescape_price_fetcher\values")
with open("incubators.txt", "a") as file:
file.write(str(list))
file.write("\n")
file.close()
print("Incubator values has now storaged at IncubatorValues class and imported to incubators.txt")
print(self)
以上是我正在嘗試構建的 OOP 循環。 Class 和 self 工作正常,但是當我列出 append 值並將其寫入“incubators.txt”時,它只寫入如下值:
[<__main__.ItemPrices object at 0x0000023A951ACFD0>]
[<__main__.ItemPrices object at 0x0000023A951ACFD0>]
[<__main__.ItemPrices object at 0x0000023A951ACFD0>]
[<__main__.ItemPrices object at 0x0000023A951ACFD0>]
[<__main__.ItemPrices object at 0x0000023A951ACFD0>]
打印 self.name、self.exaltedValue 或 self.chaosValue 時,我可以看到我設法獲取字符串和整數,但只能將對象寫入文件。 我怎樣才能將 strs 和 int 寫入文件? 謝謝你的幫助。
您可以將列表轉換為 JSON 格式,然后寫入文件。
使用這個片段:
result=json.dumps(list, default=lambda o: o.__dict__)
然后,您可以將結果寫入文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.