Is Python del a function?

Asked 2 years ago, Updated 2 years ago, 148 views

When calling a function, it calls like function name (parameter)del is used as del object. The book says del is a function, but does del have a different way of using the function? Or something other than a function?

python3 del

2022-09-22 11:15

1 Answers

The del expression is the operator and the keyword and calls function to remove the variable(1) or to delete the element of the object.

I don't know if you've ever heard of garbage collectors and reference counts.

foo1 = Foo() # Create a Foo object and let the foo1 variable refer to it.
# The reference count for the Foo object is 1
The foo2 = foo1 # foo1 refers to the foo2 variable.
# The reference count is 2
Remove delfoo1 #foo1 variable. (Note: You are not removing Foo objects!)
# The reference count is 1
Remove delfoo2 #foo2 variable.
# The reference count is 0
# GC will delete Foo object soon!

This is usually the case, even if del is not explicitly required, it is automatically removed when the variable is outside the function scope, reducing the reference count.
In the (1) example, del serves to explicitly do it.
In fact, it's ambiguous to call it a function, and it's better to call it an operator.

In the (2) example, you can still call it a function.

class Foo(object):
    def__delitem__(self, key): # function called by de obj[key]
        print(str(key)) # Usually deletes the internal element corresponding to the key.

foo = Foo()
output delfoo[42] #42. Same as foo.__delitem__(42)
delfoo["hi"] # output hi. Same as foo.__delitem_("hi")

It's not a function, but you can call it a function.
You can think of it as a grammatical sugar that invokes _delitem__.

In a broad sense, a function is called a function even if it is not grammatically a function because it is calculated by giving x and spitting out y.
In the (1) example, del, x is a variable, operation removes the variable, and y is nothing.
In the (2) example, del where x is the object and key, operation removes the element corresponding to the key from the object, and y is also nothing.
From this point of view, we can call it a function.


2022-09-22 11:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.