Skip to content

Instantly share code, notes, and snippets.

@Alexis-D
Created July 8, 2011 17:59
Show Gist options
  • Save Alexis-D/1072375 to your computer and use it in GitHub Desktop.
Save Alexis-D/1072375 to your computer and use it in GitHub Desktop.
Abusing iterator to get objects without class keyword
#!/usr/bin/env python
#-*- coding: utf-8 -*-
def Person(name, life=100):
_name = name
_life = life
def _init_():
cmd = yield
while True:
if cmd and cmd[0] in _publics_methods:
cmd = (yield _publics_methods[cmd[0]](*cmd[1:]))
else:
raise NotImplementedError('wtf?')
def eat(amount=10):
nonlocal _life
_life += amount
if _life > 100:
_life = 100
def hurt():
nonlocal _life
_life -= 10
if _life < 0:
_life = 0
def life():
nonlocal _life
return _life
def whoAmI():
nonlocal _name
nonlocal _life
print('Hello I\'m', _name, 'and my life is at', str(_life))
_publics_methods = {
# so it's easy to alias method name (if you want length and size for instance)
'eat': eat,
'hurt': hurt,
'life': life,
'whoAmI': whoAmI,
}
p = _init_()
next(p)
return p
if __name__ == '__main__':
p = Person('John', 83)
print('Life: {}'.format(p.send(('life',))))
p.send(('eat', 15))
print('Life: {}'.format(p.send(('life',))))
p.send(('whoAmI',))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment