Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def func():
- class A:
- x = 10
- y = 20
- return A
- def func():
- o = object()
- o.x = 10
- o.y = 20
- return o
- class Struct(dict):
- """Python Objects that act like Javascript Objects"""
- def __init__(self, *args, **kwargs):
- super(Struct, self).__init__(*args, **kwargs)
- self.__dict__ = self
- o = Struct(x=10)
- o.y = 20
- o['z'] = 30
- print o.x, o['y'], o.z
- from collections import namedtuple
- XYTuple = namedtuple('XYTuple', 'x y')
- nt = XYTuple._make( (10, 20) )
- print nt.x, nt.y
- >>> o = object()
- >>> o.x = 10
- AttributeError: 'object' object has no attribute 'x'
- class Struct(object):
- """
- An object whose attributes are initialized from an optional positional
- argument or from a set of keyword arguments (the constructor accepts the
- same arguments than the dict constructor).
- """
- def __init__(self, *args, **kwargs):
- self.__dict__.update(*args, **kwargs)
- def __repr__(self):
- klass = self.__class__
- attributes = ', '.join('{0}={1!r}'.format(k, v) for k, v in self.__dict__.iteritems())
- return '{0}.{1}({2})'.format(klass.__module__, klass.__name__, attributes)
- def func():
- return Struct(x = 10, y = 20)
- class Struct(dict):
- def __getattr__(self, k):
- try:
- return self[k]
- except KeyError:
- return self.__getitem__(k)
- def __setattr__(self, k, v):
- if isinstance(v, dict):
- self[k] = self.__class__(v)
- else:
- self[k] = v
- o = Struct(x=10)
- o.y = 20
- o['z'] = 30
- print(o.x, o['y'], o.z) # -> (10, 20, 30)
- print(o['not_there']) # -> KeyError: 'not_there'
- print(o.not_there) # -> KeyError: 'not_there'
Add Comment
Please, Sign In to add comment