简体   繁体   English

删除类后使用类方法和变量

[英]Using class methods and variables after deleting class

So I was messing around in the Python IDLE Shell today and I noticed something. 因此,我今天在Python IDLE Shell中乱七八糟,发现了一些东西。 I had a class like so: 我上过这样的课:

class Name:
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return self.name

I created an instance of the class and printed out the name: 我创建了该类的实例,并打印了名称:

name1 = Name("Cameron")
print(name1)

Then I deleted the class: 然后我删除了该类:

del Name

But then realized that I could still use 'name1' like nothing ever happened: 但是后来意识到我仍然可以像没有任何事情一样使用'name1':

# still returns 'Cameron'
print(name1)

Can somebody tell me why this happens? 有人可以告诉我为什么会这样吗?

del doesn't mean "destroy this thing". del并不意味着“摧毁这件事”。 It means "unassign this variable". 这意味着“不分配此变量”。 Other references to the object the variable referred to are unaffected, and as long as the object is reachable through some chain of references, it won't be destroyed. 对该变量所引用的对象的其他引用不受影响,并且只要该对象可通过某些引用链访问,就不会破坏该对象。

When you execute 执行时

del Name

the Name variable is gone, but the Name class the variable used to refer to is still around. Name变量消失了,但是用于引用的Name类仍然存在。 name1 has a reference to its type, so it will continue to work fine. name1引用了它的类型,因此它将继续正常工作。

The del statement doesn't actually delete the object. del语句实际上并没有删除该对象。 It removes the reference to the object. 它删除对对象的引用。 In this case, when you instantiate name1 = Name("Cameron") , you are making another reference to the object. 在这种情况下,当实例化name1 = Name("Cameron") ,您将对该对象进行另一个引用。 When you use del Name , it just removes one of them. 当您使用del Name ,它只会删除其中之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM