Created
January 29, 2020 22:01
-
-
Save yuwash/678d7335171199d2c192cb565781e815 to your computer and use it in GitHub Desktop.
Python closure to simulate a class
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
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