Skip to content

Instantly share code, notes, and snippets.

@antonagestam
Created December 3, 2018 20:59
Show Gist options
  • Save antonagestam/56ea25db55fb32e62516ea8dcde31766 to your computer and use it in GitHub Desktop.
Save antonagestam/56ea25db55fb32e62516ea8dcde31766 to your computer and use it in GitHub Desktop.
Example of reusing objects in Python
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