【问题标题】:Classes won't delete, or delete everything课程不会删除或删除所有内容
【发布时间】:2013-06-10 00:41:41
【问题描述】:

我已经编写了 Person 类,但是每当我使用 Del 时它什么都不做,如果我将它更改为打印,它似乎会删除所有的人,而不仅仅是我问它的那个人。任何解决此问题的帮助将不胜感激。

class Person:
    population = 0
    def __init__ (self, name, age):
        self.name = name
        self.age = age
        print ("{0} has been born!".format(self.name))
        Person.population += 1
    def __str__ (self):
        return ("{0} is {1} years young.".format(self.name, self.age))
    def __del__ (self):
        return ("{0} is dying :)".format(self.name))
        Person.population -= 1
    def Totalpop ():
        print ("There are {0} people here mate.".format(Person.population))

p1 = Person("Crumbs", 39)
p2 = Person("Harry", 89846)
p3 = Person("Amanda", 5)
print (p1)
print (p2)
print (p3)
del (p3)
print (Person.Totalpop())

【问题讨论】:

    标签: class python-3.x del


    【解决方案1】:

    正如您所建议的,在您的 __del__ 函数中放入 return 而不是 print 会在它递减 Person.population 之前终止它(并使其返回 none)。它看起来“删除所有人”的原因是因为您的程序立即结束,所以他们实际上都被删除了。删除它们的不是你的函数,它只是 Python 在退出之前清理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多