0

Some source code is like below:

class Flask(object):
    def __init__(self, value):
        self.value = value
    def _get(self):
        return self.value
    def _set(self,value):
        self.value = value
    name = property(_get, _set)
    del _get, _set
app = Flask('abc')
app.name = 'hello'

My question is why this source code block can work. Class method _get, _set was deleted by del sentences. Why we also can use app.name to call the Flask._set method?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219

2 Answers2

1

del deletes the name and the memory if nothing else references it.

Since you copied the reference when doing name = property(_get, _set), del has not the effect you're believing it has (imaging the disastrous effects of a forced deletion, for instance in a C++ code. That would make the python runtime unstable)

You cannot access _get and _set methods directly (by name), but they're still referenced somewhere.

Small, simpler example:

l=[3,4,5]
x=l
del l
print(x)
print(l)

result:

[3, 4, 5]    # <== x is valid
Traceback (most recent call last):
  File "L:\module1.py", line 5, in <module>
    print(l)
NameError: name 'l' is not defined

you see that x has kept the data. But accessing l raises NameError

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

As the comment says, they're not really deleted as there are references to them (held by the property) but they (as names) are removed from the class itself, therefore writing

app = Flask('abc')
app._get()
app._set('foo')

is not possible because Flask class no longer has these members.

Misza
  • 635
  • 4
  • 15