Say we have a class Test
which has a static method as so:
import weakref
class Test:
@staticmethod
def hello():
return 'Hello'
We create an instance of Test
- call its method, we also create a weak reference to the instance as well. Then delete the variable and see if we can call the method again:
test_ins = Test()
test_ins_weakref = weakref.ref(test_ins)
print(test_ins.hello())
print("---deleting test_ins---")
del test_ins
print(test_ins_weakref().hello())
Before we delete the instance, it works (as it should) - but then it doesn't (Checking the type yields NoneType
and it of course does not have a method called hello
).
If we don't perform the del
operation on the instance, we would get <class '__main__.Test'>
and thus we can call the method.
Now lets try deleting the class itself:
test_ins = Test()
test_ins_weakref = weakref.ref(test_ins)
print(test_ins.hello())
print("---deleting test_ins---")
del Test
print(test_ins_weakref().hello())
It works.
My main question is if someone can explain what is happening here, because when I read the code I don't understand how and why it works that way.
Deleting a whole class doesn't mean that now all its instances point to nothing? Because, after deleting the class Test
we cannot access the method nor create new instances..
new_ins = Test()
print(Test().hello())
Both yield
NameError: name 'Test' is not defined
However we can tweak things "around" and use the working instance type to create a new one:
new_ins = type(test_ins)()
print(new_ins.hello())
Works just fine.