Advertisement
p2k

Understanding the Python Data Model

p2k
Mar 2nd, 2012
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. # http://docs.python.org/reference/datamodel.html
  2.  
  3. class Demo(object):
  4.     # This method gets called on every access to self.something
  5.     # It is implemented in "object", the base class for every
  6.     # python object, and looks roughly like this:
  7.     def __getattribute__(self, name):
  8.         # Debug print
  9.         print("__getattribute__('%s')" % name)
  10.         # Look for instance attribute
  11.         d = object.__getattribute__(self, "__dict__")
  12.         if d.has_key(name):
  13.             return d[name]
  14.         # Look for class attribute
  15.         cls = object.__getattribute__(self, "__class__")
  16.         d = cls.__dict__
  17.         if d.has_key(name):
  18.             a = d[name]
  19.             # Wrap unbound methods
  20.             if callable(a):
  21.                 def bound_method(*argv, **argn):
  22.                     return a(self, *argv, **argn)
  23.                 return bound_method
  24.             else:
  25.                 return a
  26.         raise AttributeError("'%s' object has no attribute '%s'" % (cls.__name__, name))
  27.    
  28.     x = 1 # A class attribute
  29.    
  30.     def __init__(self):
  31.         self.y = 2 # An instance attribute
  32.    
  33.     def method(self, z): # A method
  34.         return self.x + self.y + z
  35.  
  36. # Try in a console:
  37. o = Demo()
  38. o.x
  39. o.y
  40. o.hello = "world"
  41. o.hello
  42. Demo.this_is = "a test"
  43. o.this_is
  44. o.method
  45. o.method(3)
  46.  
  47. # Remove the __getattribute__ implementation and re-run the tests
  48. # above to see that it does work the same way.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement