I have written the class Person, however whenever i go to use Del it doesn't do anything, and if I change it to print it seems to delete all of the people, not just the one i asked it too. Any help fixing this would be appreciated.

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())
有帮助吗?

解决方案

As you suggest, putting return instead of print in your __del__function terminates it (and makes it return none) before it decrements Person.population. The reason it appears to "delete all of the people" is because your program ends immediately afterwards, so they actually are all getting deleted. It's not your function which is deleting them, it's just Python cleaning up before it exits.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top