Skip to content

Instantly share code, notes, and snippets.

@yuwash
Created January 29, 2020 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuwash/678d7335171199d2c192cb565781e815 to your computer and use it in GitHub Desktop.
Save yuwash/678d7335171199d2c192cb565781e815 to your computer and use it in GitHub Desktop.
Python closure to simulate a class
def Tool(name):
data = {
'name': name,
'size': 0,
'color': 0xffee88,
}
def get_color():
return data['color']
def get_size():
return data['size']
def set_size(size):
data['size'] = size
def instance():
pass
instance.get_color = get_color
instance.get_size = get_size
instance.set_size = set_size
return instance
if __name__ == '__main__':
pen = Tool('pen')
print('Pen size: {}'.format(pen.get_size()))
pen.set_size(2)
brush = Tool('brush')
print('Pen size: {}'.format(pen.get_size()))
print('Brush size: {}'.format(brush.get_size()))
print('Brush color: #{:x}'.format(brush.get_color()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment