Created
August 25, 2019 08:40
-
-
Save d3rp/57021f382d16f6fb0f5b50b2dbcc2911 to your computer and use it in GitHub Desktop.
Class closure (Kind of a gotcha if done by accident)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""instance variables gotcha""" | |
class C: | |
"""Works like a closure because class body is interpreted at import time""" | |
data = {} | |
def __init__(self, input): | |
self.data.update(input) | |
c = C({'a':'b'}) | |
print(c.data) | |
# {'a': 'b'} | |
not_the_same_instance = C({'foo': 'bar'}) | |
print(not_the_same_instance.data) | |
# {'a': 'b', 'foo': 'bar'} | |
print(c.data) | |
# {'a': 'b', 'foo': 'bar'} | |
class X: | |
"""methods are interpreted at runtime, so the mutable instance variable won't work as closure""" | |
def __init__(self, input): | |
self.data = {} | |
self.data.update(input) | |
x = X({'a':'b'}) | |
print(x.data) | |
# {'a': 'b'} | |
y = X({'foo': 'bar'}) | |
print(y.data) | |
# {'foo': 'bar'} | |
print(x.data) | |
# {'a': 'b'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment