Custom Search

Sunday, April 17, 2011

python implement your own (read-only) version of property using descriptors.

python implement your own (read-only) version of property using descriptors.
When you use dotted access to look up a member (eg, x.y),
Python first looks for the member in the instance dictionary.
If it's not found, it looks for it in the class dictionary.
If it finds it in the class dictionary, and the object
implemented the descriptor protocol, instead of just
returning it, Python executes it. A descriptor is any class
that implements the __get__, __set__, or __del__ methods.
Descriptors are used in Python to implement properties,
bound methods, static methods, class methods and slots,
amongst other things.


class Property(object):
def __init__(self, fget):
print "\n----__init__---fget---", fget
self.fget = fget

def __get__(self, obj, type):
print "\n----__get__---obj---", obj
print "\n----__get__---type---", type
if obj is None:
return self
return self.fget(obj)


class MyClass(object):
@Property
def foo(self):
print "-----foo------"
return "Foo.....!"

print "\n-------start-------"
m1 = MyClass()
print "\n--------m1--------", m1
print "\n-----m1.foo-----", m1.foo

OUTPUT
======
----__init__---fget---

-------start-------

--------m1-------- <__main__.MyClass object at 0x7f155505a090>

-----m1.foo-----
----__get__---obj--- <__main__.MyClass object at 0x7f155505a090>

----__get__---type---
-----foo------
Foo.....!


More...


No comments:

Post a Comment