Created
December 3, 2018 20:59
-
-
Save antonagestam/56ea25db55fb32e62516ea8dcde31766 to your computer and use it in GitHub Desktop.
Example of reusing objects in Python
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
class Reusing: | |
__free = [] | |
def __new__(cls, *args, **kwargs): | |
try: | |
return cls.__free.pop() | |
except IndexError: | |
return super(Reusing, cls).__new__(cls) | |
def __del__(self): | |
self.__free.append(self) | |
class OhMy(Reusing): | |
def __init__(self, name): | |
try: | |
print(f'previous name: {self.name}') | |
except AttributeError: | |
pass | |
self.name = name | |
a = OhMy('a') | |
print(f'a.name: {a.name}') | |
del a | |
c = OhMy('c') | |
print(f'c.name: {c.name}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment