(python)如何删除类def中的对象

问题描述 投票:0回答:1
class Axe:
    def __init__(self, name, durability):
        self.name = name
        self.durability = durability
    def __str__(self):
        return f"{self.name}: {self.durability}"
    def use(self):
        self.durability -= 1
        if self.durability < 1:
            print(f"{self.name} broke")

超过耐久度后如何删除对象?

我尝试删除 self 和 self.self,但返回了错误。

python class
1个回答
-1
投票

您也许可以使用 del 语句来删除对象

class Axe:
    def __init__(self, name, durability):
        self.name = name
        self.durability = durability
    def __str__(self):
        return f"{self.name}: {self.durability}"
    def use(self):
        self.durability -= 1
        if self.durability < 1:
            print(f"{self.name} broke")
            del self
© www.soinside.com 2019 - 2024. All rights reserved.