SlideShare ist ein Scribd-Unternehmen logo
1 von 9
Descriptors
  jss 2011-07-07
What can you do
inside 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): pass

All 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): pass

All 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 Examples

class 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 access

class Foo(object): pass

f = 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.htm
class 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, "can't set attribute"
        self.fset(obj, value)

    def __delete__(self, obj):
        if self.fdel is None:
            raise AttributeError, "can't delete attribute"
        self.fdel(obj)

Weitere ähnliche Inhalte

Was ist angesagt?

CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest
 
Advanced python
Advanced pythonAdvanced python
Advanced python
EU Edge
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 
Python decorators
Python decoratorsPython decorators
Python decorators
Alex Su
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
Ben James
 

Was ist angesagt? (20)

Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
 
ECMA 入门
ECMA 入门ECMA 入门
ECMA 入门
 
Testing for share
Testing for share Testing for share
Testing for share
 
Advanced python
Advanced pythonAdvanced python
Advanced python
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch20170113 julia’s type system and multiple dispatch
20170113 julia’s type system and multiple dispatch
 
Namespaces
NamespacesNamespaces
Namespaces
 
Declarative Data Modeling in Python
Declarative Data Modeling in PythonDeclarative Data Modeling in Python
Declarative Data Modeling in Python
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
Swift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extensionSwift 3 Programming for iOS : extension
Swift 3 Programming for iOS : extension
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
 
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
 

Andere mochten auch

Monaqasat.com ArabNET presentation
Monaqasat.com ArabNET presentationMonaqasat.com ArabNET presentation
Monaqasat.com ArabNET presentation
Monaqasat.com
 
Rest breaks
Rest breaksRest breaks
Rest breaks
Sheila A
 
How long is the working week
How long is the working weekHow long is the working week
How long is the working week
Sheila A
 
Geografia
GeografiaGeografia
Geografia
980526
 
ForbushSchoolResumeandcv
ForbushSchoolResumeandcvForbushSchoolResumeandcv
ForbushSchoolResumeandcv
Renee Cornish
 

Andere mochten auch (20)

Monaqasat.com ArabNET presentation
Monaqasat.com ArabNET presentationMonaqasat.com ArabNET presentation
Monaqasat.com ArabNET presentation
 
Rest breaks
Rest breaksRest breaks
Rest breaks
 
How long is the working week
How long is the working weekHow long is the working week
How long is the working week
 
Ejercicio2.carlos lozano
Ejercicio2.carlos lozanoEjercicio2.carlos lozano
Ejercicio2.carlos lozano
 
Missd
MissdMissd
Missd
 
Proyecto de vida
Proyecto de vidaProyecto de vida
Proyecto de vida
 
cvnophotoA
cvnophotoAcvnophotoA
cvnophotoA
 
Preguntas deider
Preguntas deiderPreguntas deider
Preguntas deider
 
Geografia
GeografiaGeografia
Geografia
 
La Pugliese | Analisis territorial
La Pugliese | Analisis territorialLa Pugliese | Analisis territorial
La Pugliese | Analisis territorial
 
Ejemplo de estudio de mercado
Ejemplo de estudio de mercadoEjemplo de estudio de mercado
Ejemplo de estudio de mercado
 
ตัวอย่างชิ้นงาน P5 2-58
ตัวอย่างชิ้นงาน P5 2-58ตัวอย่างชิ้นงาน P5 2-58
ตัวอย่างชิ้นงาน P5 2-58
 
Ideologías políticas
Ideologías políticasIdeologías políticas
Ideologías políticas
 
Expo1 adm finac-p
Expo1 adm finac-pExpo1 adm finac-p
Expo1 adm finac-p
 
STANDARD FOR FABRICS (SUITING) PER SNI
STANDARD FOR FABRICS (SUITING) PER SNISTANDARD FOR FABRICS (SUITING) PER SNI
STANDARD FOR FABRICS (SUITING) PER SNI
 
Textile fabrics analysis
Textile fabrics analysisTextile fabrics analysis
Textile fabrics analysis
 
be proud to be an indian on independance day VRVP
be proud to be an indian on independance day VRVPbe proud to be an indian on independance day VRVP
be proud to be an indian on independance day VRVP
 
ForbushSchoolResumeandcv
ForbushSchoolResumeandcvForbushSchoolResumeandcv
ForbushSchoolResumeandcv
 
101910 open letter_to_news_media
101910 open letter_to_news_media101910 open letter_to_news_media
101910 open letter_to_news_media
 
Smart phones final
Smart phones finalSmart phones final
Smart phones final
 

Ähnlich wie Descriptor Protocol

DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
Graham Dumpleton
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
New Relic
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
Tendayi Mawushe
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
Jim Yeh
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
Felinx Lee
 
Python Descriptors Demystified
Python Descriptors DemystifiedPython Descriptors Demystified
Python Descriptors Demystified
Chris Beaumont
 

Ähnlich wie Descriptor Protocol (20)

DjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New RelicDjangoCon US 2011 - Monkeying around at New Relic
DjangoCon US 2011 - Monkeying around at New Relic
 
Djangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New RelicDjangocon11: Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in Python
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
 
Python's magic methods
Python's magic methodsPython's magic methods
Python's magic methods
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved again
 
Python decorators (中文)
Python decorators (中文)Python decorators (中文)
Python decorators (中文)
 
Design of OO language
Design of OO languageDesign of OO language
Design of OO language
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
用Tornado开发RESTful API运用
用Tornado开发RESTful API运用用Tornado开发RESTful API运用
用Tornado开发RESTful API运用
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptxPython_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptx
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Python Descriptors Demystified
Python Descriptors DemystifiedPython Descriptors Demystified
Python Descriptors Demystified
 

Mehr von rocketcircus (8)

Pytables
PytablesPytables
Pytables
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocol
 
Python Academy
Python AcademyPython Academy
Python Academy
 
intro to scikits.learn
intro to scikits.learnintro to scikits.learn
intro to scikits.learn
 
AWS Quick Intro
AWS Quick IntroAWS Quick Intro
AWS Quick Intro
 
PyPy 1.5
PyPy 1.5PyPy 1.5
PyPy 1.5
 
Message Queues
Message QueuesMessage Queues
Message Queues
 
Rocket Circus on Code Review
Rocket Circus on Code ReviewRocket Circus on Code Review
Rocket Circus on Code Review
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

Descriptor Protocol

  • 1. Descriptors jss 2011-07-07
  • 2. What can you do inside a class suite?
  • 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): pass All 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. @c_decorator1 @c_decorator0(foo=23) class Foo(object): __metaclass__ = MetaClass wenglo = 0 garply, corge = mktuple(qux) @staticmethod def fred(): pass def __new__(klass): pass All 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. 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. Generic Descriptor Examples class 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. “Normal” attribute access class Foo(object): pass f = Foo() f.bla # implemented in object.__getattribute__: == type(f).__dict__[‘bla’].__get__(f, type(f))
  • 8. Demo show some code: check out ListProperty in postamt.py
  • 9. Implementing property() # by Raymond Hettinger: http://users.rcn.com/python/download/Descriptor.htm class 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, "can't set attribute" self.fset(obj, value) def __delete__(self, obj): if self.fdel is None: raise AttributeError, "can't delete attribute" self.fdel(obj)