• Save
Descriptor Protocol
Upcoming SlideShare
Loading in...5
×
 

Descriptor Protocol

on

  • 300 views

 

Statistics

Views

Total Views
300
Views on SlideShare
300
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Descriptor Protocol Descriptor Protocol Presentation Transcript

  • Descriptors jss 2011-07-07
  • What can you doinside a class suite?
  • @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()
  • @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()
  • 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)
  • 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
  • “Normal” attribute accessclass Foo(object): passf = Foo()f.bla# implemented in object.__getattribute__:== type(f).__dict__[‘bla’].__get__(f, type(f))
  • Demo show some code:check out ListProperty in postamt.py
  • 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)