Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Descriptor Protocol

393 views

Published on

  • Be the first to comment

  • Be the first to like this

Descriptor Protocol

  1. 1. Descriptors jss 2011-07-07
  2. 2. What can you doinside a class suite?
  3. 3. @c_decorator1 @c_decorator0(foo=23) class Foo(object): __metaclass__ = MetaClass wenglo = 0 garply, corge = mktuple(qux) @staticmethod def fred(): pass def __new__(klass): passAll In One: @classmethod def wilma(klass): pass def __init__(self, *_): pass @f_decorator def foo(self, *_): pass @property def bar(self): pass @bar.setter def set_bar(self, v): pass helga = Descriptor() print locals()
  4. 4. @c_decorator1 @c_decorator0(foo=23) class Foo(object): __metaclass__ = MetaClass wenglo = 0 garply, corge = mktuple(qux) @staticmethod def fred(): pass def __new__(klass): passAll In One: @classmethod def wilma(klass): pass def __init__(self, *_): pass @f_decorator def foo(self, *_): pass @property def bar(self): pass @bar.setter def set_bar(self, v): pass helga = Descriptor() print locals()
  5. 5. Descriptor Protocol• Descriptors are customized Object Attributes• An object with any of these defined is a descriptor: __get__(self, obj, type=None) __set__(self, obj, val) __delete__(self, obj)
  6. 6. Generic Descriptor Examplesclass Foo(object): def wenglo(self): f = Foo() return self.qux f.wenglo() @classmethod Foo.foo() def foo(klass): Foo.wenglo() return klass.bar @staticmethod def buz(): return 42
  7. 7. “Normal” attribute accessclass Foo(object): passf = Foo()f.bla# implemented in object.__getattribute__:== type(f).__dict__[‘bla’].__get__(f, type(f))
  8. 8. Demo show some code:check out ListProperty in postamt.py
  9. 9. Implementing property()# by Raymond Hettinger: http://users.rcn.com/python/download/Descriptor.htmclass property(object): def __init__(self, fget=None, fset=None, fdel=None, doc=None): self.fget = fget self.fset = fset self.fdel = fdel self.__doc__ = doc def __get__(self, obj, objtype=None): if obj is None: return self if self.fget is None: raise AttributeError, "unreadable attribute" return self.fget(obj) def __set__(self, obj, value): if self.fset is None: raise AttributeError, "cant set attribute" self.fset(obj, value) def __delete__(self, obj): if self.fdel is None: raise AttributeError, "cant delete attribute" self.fdel(obj)

×