Last active
August 29, 2015 14:05
-
-
Save firstspring1845/f64f0f3b7a1e98f1ee8b to your computer and use it in GitHub Desktop.
Python用にRubyのHashie::Mashっぽいの
This file contains hidden or 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
class mash(object): | |
def __init__(self, dic={}): | |
dic = {str(k): v if v.__class__ != dict else mash(v) for (k, v) in dic.items()} | |
super(mash, self).__setattr__('_dic', dic) | |
#self.name | |
def __getattr__(self, name): | |
return self._dic[name] | |
#self.name = value | |
def __setattr__(self, name, value): | |
self._dic[str(name)] = value | |
#item in self | |
def __contains__(self, item): | |
return item in self._dic | |
#str(self) | |
def __str__(self): | |
return 'Mash:' + self._dic.__str__() | |
#repr(self) | |
def __repr__(self): | |
return 'mash(' + self._dic.__repr__() + ')' | |
def todict(self): | |
return {k: v if v.__class__ != mash else v.todict() for (k, v) in self._dic.items()} |
This file contains hidden or 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
>>> import mash | |
>>> m = mash.mash() | |
>>> m.value = 1 | |
>>> m.value | |
1 | |
>>> m.todict() | |
{'value': 1} | |
>>> 'value' in m | |
True | |
>>> 'id' in m | |
False | |
>>> m = mash.mash({'id':1024}) | |
>>> m.id | |
1024 | |
>>> 'value' in m | |
False | |
>>> 'id' in m | |
True | |
>>> m = mash.mash({'user':{'name':'John'}}) | |
>>> m.user.name | |
'John' |
This file contains hidden or 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
from mash import mash | |
import unittest | |
class mashtest(unittest.TestCase): | |
def test_set(self): | |
m = mash() | |
m.v = True | |
self.assertTrue(m.v) | |
m.m = mash() | |
m.m.v = True | |
self.assertTrue(m.m.v) | |
def test_dict(self): | |
d = {'name':'John','sex':'male','age':19} | |
m = mash(d) | |
self.assertEqual(m.name, 'John') | |
self.assertEqual(m.sex, 'male') | |
self.assertEqual(m.age, 19) | |
self.assertEqual(m.todict(), d) | |
d = {'type':'event','value':{'id':1111,'text':'Everything is OK:)'}} | |
m = mash(d) | |
self.assertEqual(m.type, 'event') | |
self.assertEqual(m.value.id, 1111) | |
self.assertEqual(m.value.text, d['value']['text']) | |
self.assertEqual(m.todict(), d) | |
self.assertEqual(m, mash(m.todict())) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
setattrをオーバーライドしているためself._dic = {}により__setattr__が呼ばれ無限ループするっぽ
super呼び出しに書き換える