python中的对象销毁

2024-04-25 11:46:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python比较陌生。让我举个例子来说明我的疑问:

我创建了名为“person”的类对象

class person:
    name = ""
    age = ""
    phones = []
    def add_phone(self, number):
        self.phones.append(number)

让我们准备一些数据以便以后使用:

^{pr2}$

让我们输入for循环:

for i in range(0,4):
    new_person = person()

据我所知,每次执行前一行时,都会创建一个新的对象person,并将其称为new_person,并且前一次迭代中变量new_person中的任何对象都应该被销毁。但事实并非如此:

    new_person.name = names[i]
    new_person.age = ages[i]
    new_person.add_phone(phones[i])

    print "i= " + str(i)
    print "name= "+ new_person.name
    print "age= "+ str(new_person.age)
    print "phones:"
    print new_person.phones

new_person.phones包含我们在先前迭代中添加的电话。有人看到我遗漏了什么吗?这是否意味着对象类“person”的行为类似于singleton?在


Tags: 对象nameselfaddnumbernewforage
3条回答

要按预期工作,需要将phones定义为实例属性。在

class person:
    name = ""
    age = ""
    def __init__(self):
        self.phones = []
    def add_phone(self, number):
        self.phones.append(number)

在您的示例中,您将phone附加到class属性中,该属性对于所有实例都是“共享的”(比如说)。在

您定义了一组类级别的属性,这些属性几乎可以肯定是实例级的。我想你想要的是:

class person:

    def __init__(self):

        self.name = ""
        self.age = ""
        self.phones = []

    def add_phone(self, number):

        self.phones.append(number)

Python中处理实例化的方式是初始化器__init__()(与其他语言中的构造函数类似但不同)创建实例属性。在Python中,将未初始化的属性设置为None而不是空字符串可能更常见。此外,通常在初始值设定项中包含常用属性:

^{pr2}$

正如你所期望的那样,这些对象正在被创建和销毁。问题是self.phones属于而不是实例,因此由{}的所有实例共享。在

要修复,请按如下方式更改类:

class person(object):
    def __init__(self):
        self.name = ""
        self.age = ""
        self.phones = []
    def add_phone(self, number):
        self.phones.append(number)

相关问题 更多 >

    热门问题