""" 如何得到变量的名字? 看似很简单的问题其实很难。 这里提供了一种参考方法。 """ class TestClass: def __init__(self): self.hashcode = id(self) self.delete_self_name() def delete_self_name(self): weizhi = [k for k, v in globals().items() if hasattr(v,'hashcode') and v.hashcode == self.hashcode] if weizhi==[]: weizhi = [k for k, v in locals().items() if hasattr(v,'hashcode') and v.hashcode == self.hashcode] name = weizhi[0] if name in globals(): globals().pop(name) elif name in locals(): locals().pop(name) def __del__(self): print("调用__del__() 销毁对象,释放其空间") ttt = TestClass() print(ttt.delete_self_name()) print(ttt) # 对象已经被删除了。
-
- 2025 年 3 月
- 2025 年 2 月
- 2025 年 1 月
- 2024 年 12 月
- 2024 年 8 月
- 2024 年 6 月
- 2024 年 5 月
- 2024 年 4 月
- 2024 年 3 月
- 2024 年 2 月
- 2023 年 11 月
- 2023 年 9 月
- 2023 年 6 月
- 2023 年 5 月
- 2023 年 4 月
- 2023 年 3 月
- 2023 年 2 月
- 2023 年 1 月
- 2022 年 12 月
- 2022 年 11 月
- 2022 年 10 月
- 2022 年 9 月
- 2022 年 8 月
- 2022 年 7 月
- 2022 年 6 月
- 2022 年 5 月
- 2022 年 4 月
- 2022 年 3 月
- 2022 年 2 月
- 2022 年 1 月
- 2021 年 12 月
- 2021 年 11 月
- 2021 年 10 月
- 2021 年 9 月
- 2021 年 8 月
- 2021 年 7 月
- 2021 年 6 月
- 2021 年 5 月
- 2021 年 4 月
- 2021 年 3 月
- 2021 年 2 月
- 2021 年 1 月
- 2020 年 12 月
- 2020 年 11 月
- 2020 年 10 月
- 2020 年 9 月
- 2020 年 8 月
- 2020 年 7 月
- 2020 年 6 月
- 2020 年 5 月
- 2020 年 4 月
- 2020 年 3 月
- 2020 年 2 月
- 2020 年 1 月
- 2019 年 12 月
- 2019 年 11 月
- 2019 年 10 月
- 2019 年 9 月
- 2019 年 8 月
- 2019 年 7 月
- 2019 年 6 月
- 2019 年 5 月
- 2019 年 4 月
- 2019 年 3 月
- 2019 年 2 月
- 2018 年 3 月
- 2018 年 1 月
- 2017 年 9 月
- 2017 年 5 月
- 2017 年 1 月