Skip to content

Instantly share code, notes, and snippets.

@haridas
Created January 22, 2012 18:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haridas/1657928 to your computer and use it in GitHub Desktop.
Save haridas/1657928 to your computer and use it in GitHub Desktop.
Intercept Class attributes - Python
"""
Intercept class attributes, and more aboute the discriptors.
Discriptors - Assign a class object to an attribute of another class.
"""
class MetaClass(type):
#This attribute interceptor works when we call the class attributes.
def __getattribute__(self,attr):
print 'Inside Metaclass - class of a class : '
print "class: {}, attribute: {}".format(self,attr)
super(MetaClass,self).__getattribute__(attr)
def __setattr__(self,attr,value):
#print "Attribute setter inside Metaclass.. : "
#print "Class : {}, Attribute: {}, Value: {}".format(self,attr,value)
#Prevent the infinite loop via preventing __setattr__ again.
#self.__dict__[attr] = value
#This will call __setattr__ again.. so no use here.
#setattr(self,attr,value)
pass
class Discriptor(object):
def __get__(self,instance,owner):
"This function will be called up on the attribute featch."
print instance,owner
return instance._name
def __set__(self, instance,value):
"While Attribute settings."
print instance, value
instance._name = value
def __delete__(self,instance):
print instance
del instance._name
class Class1(object):
#__metaclass__ = MetaClass
_name = Discriptor()
_age = 22
@property
def age(self):
return self._age
@age.setter
def age(self,value):
self._age = value
#This attribute intercepter works only with instnce of a class.
def __getattribute__(self,value):
print "getting value"
#Lot of funky patching :)
if __name__ == '__main__':
print "======== class attribute fetching and interception. ====="
#Class1.test
Class1.test1 = 'test'
c = Class1()
c.asdsa
#Class1.asdfds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment