【问题标题】:Converting OOP objects to text in Python在 Python 中将 OOP 对象转换为文本
【发布时间】:2022-01-22 11:59:12
【问题描述】:

我仍然是 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 循环。班级和自我工作完美,但是当我 将值附加到列表并将其写入“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 写入文件?感谢您的帮助。

【问题讨论】:

  • 请更新代码的缩进。 Python 对缩进非常敏感,python 程序员也是如此。
  • 是的,第二个 def 不恰当地为此感到抱歉!
  • 这能回答你的问题吗? How to print instances of a class using print()?
  • 遗憾的是没有。当我实现它时没有工作。

标签: python oop


【解决方案1】:

您可以将列表转换为 JSON 格式,然后写入文件。

使用这个 sn-p :

result=json.dumps(list, default=lambda o: o.__dict__)

然后,您可以将结果写入文件中

【讨论】:

    猜你喜欢
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2020-10-06
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多