Guest User

Untitled

a guest
Oct 17th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. def func():
  2. class A:
  3. x = 10
  4. y = 20
  5. return A
  6.  
  7. def func():
  8. o = object()
  9. o.x = 10
  10. o.y = 20
  11. return o
  12.  
  13. class Struct(dict):
  14. """Python Objects that act like Javascript Objects"""
  15. def __init__(self, *args, **kwargs):
  16. super(Struct, self).__init__(*args, **kwargs)
  17. self.__dict__ = self
  18.  
  19. o = Struct(x=10)
  20. o.y = 20
  21. o['z'] = 30
  22. print o.x, o['y'], o.z
  23.  
  24. from collections import namedtuple
  25.  
  26. XYTuple = namedtuple('XYTuple', 'x y')
  27. nt = XYTuple._make( (10, 20) )
  28.  
  29. print nt.x, nt.y
  30.  
  31. >>> o = object()
  32. >>> o.x = 10
  33. AttributeError: 'object' object has no attribute 'x'
  34.  
  35. class Struct(object):
  36. """
  37. An object whose attributes are initialized from an optional positional
  38. argument or from a set of keyword arguments (the constructor accepts the
  39. same arguments than the dict constructor).
  40. """
  41.  
  42. def __init__(self, *args, **kwargs):
  43. self.__dict__.update(*args, **kwargs)
  44.  
  45. def __repr__(self):
  46. klass = self.__class__
  47. attributes = ', '.join('{0}={1!r}'.format(k, v) for k, v in self.__dict__.iteritems())
  48. return '{0}.{1}({2})'.format(klass.__module__, klass.__name__, attributes)
  49.  
  50. def func():
  51. return Struct(x = 10, y = 20)
  52.  
  53. class Struct(dict):
  54. def __getattr__(self, k):
  55. try:
  56. return self[k]
  57. except KeyError:
  58. return self.__getitem__(k)
  59.  
  60. def __setattr__(self, k, v):
  61. if isinstance(v, dict):
  62. self[k] = self.__class__(v)
  63. else:
  64. self[k] = v
  65.  
  66.  
  67. o = Struct(x=10)
  68. o.y = 20
  69. o['z'] = 30
  70. print(o.x, o['y'], o.z) # -> (10, 20, 30)
  71. print(o['not_there']) # -> KeyError: 'not_there'
  72. print(o.not_there) # -> KeyError: 'not_there'
Add Comment
Please, Sign In to add comment