python dict to object

2022-05-27  本文已影响0人  空口言_1d2e
class Struct:
    def __init__(self, **entries):
        self.__dict__.update(entries)

args = {'a': 1, 'b': 2}
s = Struct(**args)
print(dir(s))

# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'b']

class Foo(dict):

    def __init__(self, *args, **ks):
        super(Foo, self).__init__(*args, **ks)

    def __getattr__(self, item):
        return self[item]


print(dir(Foo))

a = Foo({"aa":"bb"})
print(a.aa)
print(a.get("aa"))
print(a["aa"])

# ['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
# bb
# bb
# bb
上一篇 下一篇

猜你喜欢

热点阅读