Created
January 22, 2012 18:06
-
-
Save haridas/1657928 to your computer and use it in GitHub Desktop.
Intercept Class attributes - Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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