Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://docs.python.org/reference/datamodel.html
- class Demo(object):
- # This method gets called on every access to self.something
- # It is implemented in "object", the base class for every
- # python object, and looks roughly like this:
- def __getattribute__(self, name):
- # Debug print
- print("__getattribute__('%s')" % name)
- # Look for instance attribute
- d = object.__getattribute__(self, "__dict__")
- if d.has_key(name):
- return d[name]
- # Look for class attribute
- cls = object.__getattribute__(self, "__class__")
- d = cls.__dict__
- if d.has_key(name):
- a = d[name]
- # Wrap unbound methods
- if callable(a):
- def bound_method(*argv, **argn):
- return a(self, *argv, **argn)
- return bound_method
- else:
- return a
- raise AttributeError("'%s' object has no attribute '%s'" % (cls.__name__, name))
- x = 1 # A class attribute
- def __init__(self):
- self.y = 2 # An instance attribute
- def method(self, z): # A method
- return self.x + self.y + z
- # Try in a console:
- o = Demo()
- o.x
- o.y
- o.hello = "world"
- o.hello
- Demo.this_is = "a test"
- o.this_is
- o.method
- o.method(3)
- # Remove the __getattribute__ implementation and re-run the tests
- # above to see that it does work the same way.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement