-
-
Save marioidival/28021fb6322c10ff070c to your computer and use it in GitHub Desktop.
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
""" | |
========================================================= | |
Classe ObjetoJS: imitação simples de um objeto JavaScript | |
========================================================= | |
Uma instância é construída passando argumentos nomeados: | |
>>> o = ObjetoJS(z=33, x=11, y=22) | |
A representação textual de uma instância parece a chamada do | |
construtor, mas com os argumentos exibidos sempre em ordem | |
alfabética (para facilitar os testes): | |
>>> o | |
ObjetoJS(x=11, y=22, z=33) | |
Os atributos podem ser acessados usando a notação `obj.atr`: | |
>>> o.y | |
22 | |
Ou ainda a notação `obj['atr']`: | |
>>> o['y'] | |
22 | |
Também é possível criar novos atributos usando as duas notações: | |
>>> o.peso = 100 | |
>>> o | |
ObjetoJS(peso=100, x=11, y=22, z=33) | |
>>> o['sabor'] = 'morango' | |
>>> o | |
ObjetoJS(peso=100, sabor='morango', x=11, y=22, z=33) | |
""" | |
class ObjetoJS(dict): | |
def __init__(self, **kw): | |
self.update(kw) | |
def __getattr__(self, attr): | |
return self.get(attr, None) | |
def __setattr__(self, attr, value): | |
self[attr] = value | |
def __repr__(self): | |
args = [] | |
for key, value in self.items(): | |
args.append("{}={!r}".format(key, value)) | |
args_formatted = ", ".join(sorted(args)) | |
return "ObjetoJS({})".format(args_formatted) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment