简体   繁体   中英

Using class methods and variables after deleting class

So I was messing around in the Python IDLE Shell today and I noticed something. 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:

# still returns 'Cameron'
print(name1)

Can somebody tell me why this happens?

del doesn't mean "destroy this thing". 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. name1 has a reference to its type, so it will continue to work fine.

The del statement doesn't actually delete the object. It removes the reference to the object. In this case, when you instantiate name1 = Name("Cameron") , you are making another reference to the object. When you use del Name , it just removes one of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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