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.
915 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
572 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
581 PHP ssh2_scp_send fails to send files as intended
618 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.