SlideShare ist ein Scribd-Unternehmen logo
1 von 233
Downloaden Sie, um offline zu lesen
Object Oriented Programming in Python

                                     Juan Manuel Gimeno Illa
                                       jmgimeno@diei.udl.cat

                                         Curs 2009-2010




J.M.Gimeno (jmgimeno@diei.udl.cat)          OOP in Python      Curs 2009-2010   1 / 49
Outline
 1   Introduction
 2   Classes
 3   Instances I
 4   Descriptors
       Referencing Attributes
       Bound and Unbound Methods
       Properties
       Class-Level Methods
 5   Inheritance
       Method Resolution Order
       Cooperative Superclasses
 6   Instances II

J.M.Gimeno (jmgimeno@diei.udl.cat)   OOP in Python   Curs 2009-2010   2 / 49
Introduction


Programming Paradigms

        A programming paradigm consists in the basic concepts into which
        our programs are made of
         Procedural Modules, data structures and procedures that operate
                     upon them
          Objectural Objects which encapsulate state and behaviour and
                     messages passed between these objects
          Functional Functions and closures, recursion, lists, ...
        Python is a multiparadigm programming language
               this allows the programmer to choose the paradigm that best suits the
               problem
               this allows the program to mix paradigms
               this allows the program to evolve switching paradigm if necessary



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python            Curs 2009-2010   3 / 49
Introduction


Programming Paradigms

        A programming paradigm consists in the basic concepts into which
        our programs are made of
         Procedural Modules, data structures and procedures that operate
                     upon them
          Objectural Objects which encapsulate state and behaviour and
                     messages passed between these objects
          Functional Functions and closures, recursion, lists, ...
        Python is a multiparadigm programming language
               this allows the programmer to choose the paradigm that best suits the
               problem
               this allows the program to mix paradigms
               this allows the program to evolve switching paradigm if necessary



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python            Curs 2009-2010   3 / 49
Introduction


Programming Paradigms

        A programming paradigm consists in the basic concepts into which
        our programs are made of
         Procedural Modules, data structures and procedures that operate
                     upon them
          Objectural Objects which encapsulate state and behaviour and
                     messages passed between these objects
          Functional Functions and closures, recursion, lists, ...
        Python is a multiparadigm programming language
               this allows the programmer to choose the paradigm that best suits the
               problem
               this allows the program to mix paradigms
               this allows the program to evolve switching paradigm if necessary



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python            Curs 2009-2010   3 / 49
Introduction


Programming Paradigms

        A programming paradigm consists in the basic concepts into which
        our programs are made of
         Procedural Modules, data structures and procedures that operate
                     upon them
          Objectural Objects which encapsulate state and behaviour and
                     messages passed between these objects
          Functional Functions and closures, recursion, lists, ...
        Python is a multiparadigm programming language
               this allows the programmer to choose the paradigm that best suits the
               problem
               this allows the program to mix paradigms
               this allows the program to evolve switching paradigm if necessary



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python            Curs 2009-2010   3 / 49
Introduction


Programming Paradigms

        A programming paradigm consists in the basic concepts into which
        our programs are made of
         Procedural Modules, data structures and procedures that operate
                     upon them
          Objectural Objects which encapsulate state and behaviour and
                     messages passed between these objects
          Functional Functions and closures, recursion, lists, ...
        Python is a multiparadigm programming language
               this allows the programmer to choose the paradigm that best suits the
               problem
               this allows the program to mix paradigms
               this allows the program to evolve switching paradigm if necessary



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python            Curs 2009-2010   3 / 49
Introduction


Programming Paradigms

        A programming paradigm consists in the basic concepts into which
        our programs are made of
         Procedural Modules, data structures and procedures that operate
                     upon them
          Objectural Objects which encapsulate state and behaviour and
                     messages passed between these objects
          Functional Functions and closures, recursion, lists, ...
        Python is a multiparadigm programming language
               this allows the programmer to choose the paradigm that best suits the
               problem
               this allows the program to mix paradigms
               this allows the program to evolve switching paradigm if necessary



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python            Curs 2009-2010   3 / 49
Introduction


Programming Paradigms

        A programming paradigm consists in the basic concepts into which
        our programs are made of
         Procedural Modules, data structures and procedures that operate
                     upon them
          Objectural Objects which encapsulate state and behaviour and
                     messages passed between these objects
          Functional Functions and closures, recursion, lists, ...
        Python is a multiparadigm programming language
               this allows the programmer to choose the paradigm that best suits the
               problem
               this allows the program to mix paradigms
               this allows the program to evolve switching paradigm if necessary



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python            Curs 2009-2010   3 / 49
Introduction


Programming Paradigms

        A programming paradigm consists in the basic concepts into which
        our programs are made of
         Procedural Modules, data structures and procedures that operate
                     upon them
          Objectural Objects which encapsulate state and behaviour and
                     messages passed between these objects
          Functional Functions and closures, recursion, lists, ...
        Python is a multiparadigm programming language
               this allows the programmer to choose the paradigm that best suits the
               problem
               this allows the program to mix paradigms
               this allows the program to evolve switching paradigm if necessary



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python            Curs 2009-2010   3 / 49
Classes


Python classes

 A class is a python object with several characteristics:
        You can call a class as it where a function and this call returns a new
        instance of the class
        A class has arbitrary named attributes that can be bound, unbound
        an referenced
        The class attributes can be descriptors (including functions) or normal
        data objects
        Class attributes bound to functions are also known as methods
        A method can have special python-defined meaning (they’re named
        with two leading and trailing underscores)
        A class clan inherit from other classes, meaning it delegates to other
        classes the look-up of attributes that are not found in the class itself


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python              Curs 2009-2010   4 / 49
Classes


Python classes

 A class is a python object with several characteristics:
        You can call a class as it where a function and this call returns a new
        instance of the class
        A class has arbitrary named attributes that can be bound, unbound
        an referenced
        The class attributes can be descriptors (including functions) or normal
        data objects
        Class attributes bound to functions are also known as methods
        A method can have special python-defined meaning (they’re named
        with two leading and trailing underscores)
        A class clan inherit from other classes, meaning it delegates to other
        classes the look-up of attributes that are not found in the class itself


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python              Curs 2009-2010   4 / 49
Classes


Python classes

 A class is a python object with several characteristics:
        You can call a class as it where a function and this call returns a new
        instance of the class
        A class has arbitrary named attributes that can be bound, unbound
        an referenced
        The class attributes can be descriptors (including functions) or normal
        data objects
        Class attributes bound to functions are also known as methods
        A method can have special python-defined meaning (they’re named
        with two leading and trailing underscores)
        A class clan inherit from other classes, meaning it delegates to other
        classes the look-up of attributes that are not found in the class itself


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python              Curs 2009-2010   4 / 49
Classes


Python classes

 A class is a python object with several characteristics:
        You can call a class as it where a function and this call returns a new
        instance of the class
        A class has arbitrary named attributes that can be bound, unbound
        an referenced
        The class attributes can be descriptors (including functions) or normal
        data objects
        Class attributes bound to functions are also known as methods
        A method can have special python-defined meaning (they’re named
        with two leading and trailing underscores)
        A class clan inherit from other classes, meaning it delegates to other
        classes the look-up of attributes that are not found in the class itself


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python              Curs 2009-2010   4 / 49
Classes


Python classes

 A class is a python object with several characteristics:
        You can call a class as it where a function and this call returns a new
        instance of the class
        A class has arbitrary named attributes that can be bound, unbound
        an referenced
        The class attributes can be descriptors (including functions) or normal
        data objects
        Class attributes bound to functions are also known as methods
        A method can have special python-defined meaning (they’re named
        with two leading and trailing underscores)
        A class clan inherit from other classes, meaning it delegates to other
        classes the look-up of attributes that are not found in the class itself


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python              Curs 2009-2010   4 / 49
Classes


Python classes

 A class is a python object with several characteristics:
        You can call a class as it where a function and this call returns a new
        instance of the class
        A class has arbitrary named attributes that can be bound, unbound
        an referenced
        The class attributes can be descriptors (including functions) or normal
        data objects
        Class attributes bound to functions are also known as methods
        A method can have special python-defined meaning (they’re named
        with two leading and trailing underscores)
        A class clan inherit from other classes, meaning it delegates to other
        classes the look-up of attributes that are not found in the class itself


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python              Curs 2009-2010   4 / 49
Classes


Object models
        Since Python2.2 there co-exist two slightly different object models in
        the language
        Old-style (classic) classes This is the model existing prior to
                      Python2.2
        New-style classes This is the preferred model for new code

    Old-style                                  New-style
    >>> class A: pass                          >>> class A(object): pass
    >>> class B: pass                          >>> class B(object): pass
    >>> a, b = A(), B()                        >>> a, b = A(), B()
    >>> type(a) == type(b)                     >>> type(a) == type(b)
    True                                       False
    >>> type(a)                                >>> type(a)
    <type ’instance’>                          <class ’ main .A’>


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   5 / 49
Classes


Object models
        Since Python2.2 there co-exist two slightly different object models in
        the language
        Old-style (classic) classes This is the model existing prior to
                      Python2.2
        New-style classes This is the preferred model for new code

    Old-style                                  New-style
    >>> class A: pass                          >>> class A(object): pass
    >>> class B: pass                          >>> class B(object): pass
    >>> a, b = A(), B()                        >>> a, b = A(), B()
    >>> type(a) == type(b)                     >>> type(a) == type(b)
    True                                       False
    >>> type(a)                                >>> type(a)
    <type ’instance’>                          <class ’ main .A’>


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   5 / 49
Classes


Object models
        Since Python2.2 there co-exist two slightly different object models in
        the language
        Old-style (classic) classes This is the model existing prior to
                      Python2.2
        New-style classes This is the preferred model for new code

    Old-style                                  New-style
    >>> class A: pass                          >>> class A(object): pass
    >>> class B: pass                          >>> class B(object): pass
    >>> a, b = A(), B()                        >>> a, b = A(), B()
    >>> type(a) == type(b)                     >>> type(a) == type(b)
    True                                       False
    >>> type(a)                                >>> type(a)
    <type ’instance’>                          <class ’ main .A’>


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   5 / 49
Classes


Object models
        Since Python2.2 there co-exist two slightly different object models in
        the language
        Old-style (classic) classes This is the model existing prior to
                      Python2.2
        New-style classes This is the preferred model for new code

    Old-style                                  New-style
    >>> class A: pass                          >>> class A(object): pass
    >>> class B: pass                          >>> class B(object): pass
    >>> a, b = A(), B()                        >>> a, b = A(), B()
    >>> type(a) == type(b)                     >>> type(a) == type(b)
    True                                       False
    >>> type(a)                                >>> type(a)
    <type ’instance’>                          <class ’ main .A’>


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   5 / 49
Classes


Object models
        Since Python2.2 there co-exist two slightly different object models in
        the language
        Old-style (classic) classes This is the model existing prior to
                      Python2.2
        New-style classes This is the preferred model for new code

    Old-style                                  New-style
    >>> class A: pass                          >>> class A(object): pass
    >>> class B: pass                          >>> class B(object): pass
    >>> a, b = A(), B()                        >>> a, b = A(), B()
    >>> type(a) == type(b)                     >>> type(a) == type(b)
    True                                       False
    >>> type(a)                                >>> type(a)
    <type ’instance’>                          <class ’ main .A’>


J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   5 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


New-style classes

        Defined in the type and class unification effort in python2.2
        (Introduced without breaking backwards compatibility)
        Simpler, more regular and more powerful
               Built-in types (e.g. dict) can be subclassed
               Properties: attributes managed by get/set methods
               Static and class methods (via descriptor API)
               Cooperative classes (sane multiple inheritance)
               Meta-class programming
        It will be the default (and unique) in the future
        Documents:
               Unifying types and classes in Python 2.2
               PEP-252: Making types look more like classes
               PEP-253: Subtyping built-in types



J.M.Gimeno (jmgimeno@diei.udl.cat)     OOP in Python               Curs 2009-2010   6 / 49
Classes


The class statement
             class classname(base-classes):
                 statement(s)


          classname is a variable that gets (re)bound to the class object after
          the class statement finishes executing
          base-classes is a comma separated series of expressions whose
          values must be classes
               if it does not exists, the created class is old-style
               if all base-classes are old-style, the created class is old-style
               otherwise it is a new-style class1
               since every type subclasses built-in object, we can use object to
               mark a class as new-style when no true bases exist
          The statements (a.k.a. the class body) define the set of class
          attributes which will be shared by all instances of the class
     1
         We are not considering      metaclass       now
J.M.Gimeno (jmgimeno@diei.udl.cat)          OOP in Python           Curs 2009-2010   7 / 49
Classes


The class statement
             class classname(base-classes):
                 statement(s)


          classname is a variable that gets (re)bound to the class object after
          the class statement finishes executing
          base-classes is a comma separated series of expressions whose
          values must be classes
               if it does not exists, the created class is old-style
               if all base-classes are old-style, the created class is old-style
               otherwise it is a new-style class1
               since every type subclasses built-in object, we can use object to
               mark a class as new-style when no true bases exist
          The statements (a.k.a. the class body) define the set of class
          attributes which will be shared by all instances of the class
     1
         We are not considering      metaclass       now
J.M.Gimeno (jmgimeno@diei.udl.cat)          OOP in Python           Curs 2009-2010   7 / 49
Classes


The class statement
             class classname(base-classes):
                 statement(s)


          classname is a variable that gets (re)bound to the class object after
          the class statement finishes executing
          base-classes is a comma separated series of expressions whose
          values must be classes
               if it does not exists, the created class is old-style
               if all base-classes are old-style, the created class is old-style
               otherwise it is a new-style class1
               since every type subclasses built-in object, we can use object to
               mark a class as new-style when no true bases exist
          The statements (a.k.a. the class body) define the set of class
          attributes which will be shared by all instances of the class
     1
         We are not considering      metaclass       now
J.M.Gimeno (jmgimeno@diei.udl.cat)          OOP in Python           Curs 2009-2010   7 / 49
Classes


The class statement
             class classname(base-classes):
                 statement(s)


          classname is a variable that gets (re)bound to the class object after
          the class statement finishes executing
          base-classes is a comma separated series of expressions whose
          values must be classes
               if it does not exists, the created class is old-style
               if all base-classes are old-style, the created class is old-style
               otherwise it is a new-style class1
               since every type subclasses built-in object, we can use object to
               mark a class as new-style when no true bases exist
          The statements (a.k.a. the class body) define the set of class
          attributes which will be shared by all instances of the class
     1
         We are not considering      metaclass       now
J.M.Gimeno (jmgimeno@diei.udl.cat)          OOP in Python           Curs 2009-2010   7 / 49
Classes


The class statement
             class classname(base-classes):
                 statement(s)


          classname is a variable that gets (re)bound to the class object after
          the class statement finishes executing
          base-classes is a comma separated series of expressions whose
          values must be classes
               if it does not exists, the created class is old-style
               if all base-classes are old-style, the created class is old-style
               otherwise it is a new-style class1
               since every type subclasses built-in object, we can use object to
               mark a class as new-style when no true bases exist
          The statements (a.k.a. the class body) define the set of class
          attributes which will be shared by all instances of the class
     1
         We are not considering      metaclass       now
J.M.Gimeno (jmgimeno@diei.udl.cat)          OOP in Python           Curs 2009-2010   7 / 49
Classes


The class statement
             class classname(base-classes):
                 statement(s)


          classname is a variable that gets (re)bound to the class object after
          the class statement finishes executing
          base-classes is a comma separated series of expressions whose
          values must be classes
               if it does not exists, the created class is old-style
               if all base-classes are old-style, the created class is old-style
               otherwise it is a new-style class1
               since every type subclasses built-in object, we can use object to
               mark a class as new-style when no true bases exist
          The statements (a.k.a. the class body) define the set of class
          attributes which will be shared by all instances of the class
     1
         We are not considering      metaclass       now
J.M.Gimeno (jmgimeno@diei.udl.cat)          OOP in Python           Curs 2009-2010   7 / 49
Classes


The class statement
             class classname(base-classes):
                 statement(s)


          classname is a variable that gets (re)bound to the class object after
          the class statement finishes executing
          base-classes is a comma separated series of expressions whose
          values must be classes
               if it does not exists, the created class is old-style
               if all base-classes are old-style, the created class is old-style
               otherwise it is a new-style class1
               since every type subclasses built-in object, we can use object to
               mark a class as new-style when no true bases exist
          The statements (a.k.a. the class body) define the set of class
          attributes which will be shared by all instances of the class
     1
         We are not considering      metaclass       now
J.M.Gimeno (jmgimeno@diei.udl.cat)          OOP in Python           Curs 2009-2010   7 / 49
Classes


The class statement
             class classname(base-classes):
                 statement(s)


          classname is a variable that gets (re)bound to the class object after
          the class statement finishes executing
          base-classes is a comma separated series of expressions whose
          values must be classes
               if it does not exists, the created class is old-style
               if all base-classes are old-style, the created class is old-style
               otherwise it is a new-style class1
               since every type subclasses built-in object, we can use object to
               mark a class as new-style when no true bases exist
          The statements (a.k.a. the class body) define the set of class
          attributes which will be shared by all instances of the class
     1
         We are not considering      metaclass       now
J.M.Gimeno (jmgimeno@diei.udl.cat)          OOP in Python           Curs 2009-2010   7 / 49
Classes


Attributes of class objects
 Attributes can be bound inside or outside the class body.

    >>> class C1(object):                      >>> class C2(object): pass
    ...     x = 23                             >>> C2.x = 23
    >>> print C1.x                             >>> print C2.x
    23                                         23

 Some attributes are implicitly set:
 >>>    print C1. name , C1. bases
 C1,    (<type ’object’>,)
 >>>    C1. dict [’z’] = 42
 >>>    print C1.z
 42
 >>>    print C1. dict [’x’]
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   8 / 49
Classes


Attributes of class objects
 Attributes can be bound inside or outside the class body.

    >>> class C1(object):                      >>> class C2(object): pass
    ...     x = 23                             >>> C2.x = 23
    >>> print C1.x                             >>> print C2.x
    23                                         23

 Some attributes are implicitly set:
 >>>    print C1. name , C1. bases
 C1,    (<type ’object’>,)
 >>>    C1. dict [’z’] = 42
 >>>    print C1.z
 42
 >>>    print C1. dict [’x’]
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   8 / 49
Classes


Attributes of class objects
 Attributes can be bound inside or outside the class body.

    >>> class C1(object):                      >>> class C2(object): pass
    ...     x = 23                             >>> C2.x = 23
    >>> print C1.x                             >>> print C2.x
    23                                         23

 Some attributes are implicitly set:
 >>>    print C1. name , C1. bases
 C1,    (<type ’object’>,)
 >>>    C1. dict [’z’] = 42
 >>>    print C1.z
 42
 >>>    print C1. dict [’x’]
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   8 / 49
Classes


Attributes of class objects
 Attributes can be bound inside or outside the class body.

    >>> class C1(object):                      >>> class C2(object): pass
    ...     x = 23                             >>> C2.x = 23
    >>> print C1.x                             >>> print C2.x
    23                                         23

 Some attributes are implicitly set:
 >>>    print C1. name , C1. bases
 C1,    (<type ’object’>,)
 >>>    C1. dict [’z’] = 42
 >>>    print C1.z
 42
 >>>    print C1. dict [’x’]
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   8 / 49
Classes


Attributes of class objects
 Attributes can be bound inside or outside the class body.

    >>> class C1(object):                      >>> class C2(object): pass
    ...     x = 23                             >>> C2.x = 23
    >>> print C1.x                             >>> print C2.x
    23                                         23

 Some attributes are implicitly set:
 >>>    print C1. name , C1. bases
 C1,    (<type ’object’>,)
 >>>    C1. dict [’z’] = 42
 >>>    print C1.z
 42
 >>>    print C1. dict [’x’]
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   8 / 49
Classes


Attributes of class objects
 Attributes can be bound inside or outside the class body.

    >>> class C1(object):                      >>> class C2(object): pass
    ...     x = 23                             >>> C2.x = 23
    >>> print C1.x                             >>> print C2.x
    23                                         23

 Some attributes are implicitly set:
 >>>    print C1. name , C1. bases
 C1,    (<type ’object’>,)
 >>>    C1. dict [’z’] = 42
 >>>    print C1.z
 42
 >>>    print C1. dict [’x’]
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   8 / 49
Classes


Attributes of class objects
 Attributes can be bound inside or outside the class body.

    >>> class C1(object):                      >>> class C2(object): pass
    ...     x = 23                             >>> C2.x = 23
    >>> print C1.x                             >>> print C2.x
    23                                         23

 Some attributes are implicitly set:
 >>>    print C1. name , C1. bases
 C1,    (<type ’object’>,)
 >>>    C1. dict [’z’] = 42
 >>>    print C1.z
 42
 >>>    print C1. dict [’x’]
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python           Curs 2009-2010   8 / 49
Classes


Accessing class attributes
 In statements directly inside the class’ body:

 >>> class C3(object):
 ...     x = 23
 ...     y = x + 19


 In statements in methods of the class:
 >>> class C4(object):
 ...     x = 23
 ...     def amethod(self):
 ...         print C4.x


 In statements outside the class:
 >>> class C3(object):
 ...     x = 23
 >>> C3.x = 42

J.M.Gimeno (jmgimeno@diei.udl.cat)      OOP in Python   Curs 2009-2010   9 / 49
Classes


Accessing class attributes
 In statements directly inside the class’ body:

 >>> class C3(object):
 ...     x = 23
 ...     y = x + 19


 In statements in methods of the class:
 >>> class C4(object):
 ...     x = 23
 ...     def amethod(self):
 ...         print C4.x


 In statements outside the class:
 >>> class C3(object):
 ...     x = 23
 >>> C3.x = 42

J.M.Gimeno (jmgimeno@diei.udl.cat)      OOP in Python   Curs 2009-2010   9 / 49
Classes


Accessing class attributes
 In statements directly inside the class’ body:

 >>> class C3(object):
 ...     x = 23
 ...     y = x + 19


 In statements in methods of the class:
 >>> class C4(object):
 ...     x = 23
 ...     def amethod(self):
 ...         print C4.x


 In statements outside the class:
 >>> class C3(object):
 ...     x = 23
 >>> C3.x = 42

J.M.Gimeno (jmgimeno@diei.udl.cat)      OOP in Python   Curs 2009-2010   9 / 49
Classes


Accessing class attributes
 In statements directly inside the class’ body:

 >>> class C3(object):
 ...     x = 23
 ...     y = x + 19


 In statements in methods of the class:
 >>> class C4(object):
 ...     x = 23
 ...     def amethod(self):
 ...         print C4.x


 In statements outside the class:
 >>> class C3(object):
 ...     x = 23
 >>> C3.x = 42

J.M.Gimeno (jmgimeno@diei.udl.cat)      OOP in Python   Curs 2009-2010   9 / 49
Classes


Accessing class attributes
 In statements directly inside the class’ body:

 >>> class C3(object):
 ...     x = 23
 ...     y = x + 19


 In statements in methods of the class:
 >>> class C4(object):
 ...     x = 23
 ...     def amethod(self):
 ...         print C4.x


 In statements outside the class:
 >>> class C3(object):
 ...     x = 23
 >>> C3.x = 42

J.M.Gimeno (jmgimeno@diei.udl.cat)      OOP in Python   Curs 2009-2010   9 / 49
Classes


Accessing class attributes
 In statements directly inside the class’ body:

 >>> class C3(object):
 ...     x = 23
 ...     y = x + 19


 In statements in methods of the class:
 >>> class C4(object):
 ...     x = 23
 ...     def amethod(self):
 ...         print C4.x


 In statements outside the class:
 >>> class C3(object):
 ...     x = 23
 >>> C3.x = 42

J.M.Gimeno (jmgimeno@diei.udl.cat)      OOP in Python   Curs 2009-2010   9 / 49
Classes


Accessing class attributes
 In statements directly inside the class’ body:

 >>> class C3(object):
 ...     x = 23
 ...     y = x + 19


 In statements in methods of the class:
 >>> class C4(object):
 ...     x = 23
 ...     def amethod(self):
 ...         print C4.x


 In statements outside the class:
 >>> class C3(object):
 ...     x = 23
 >>> C3.x = 42

J.M.Gimeno (jmgimeno@diei.udl.cat)      OOP in Python   Curs 2009-2010   9 / 49
Classes


Accessing class attributes
 In statements directly inside the class’ body:

 >>> class C3(object):
 ...     x = 23
 ...     y = x + 19


 In statements in methods of the class:
 >>> class C4(object):
 ...     x = 23
 ...     def amethod(self):
 ...         print C4.x


 In statements outside the class:
 >>> class C3(object):
 ...     x = 23
 >>> C3.x = 42

J.M.Gimeno (jmgimeno@diei.udl.cat)      OOP in Python   Curs 2009-2010   9 / 49
Classes


Accessing class attributes
 In statements directly inside the class’ body:

 >>> class C3(object):
 ...     x = 23
 ...     y = x + 19


 In statements in methods of the class:
 >>> class C4(object):
 ...     x = 23
 ...     def amethod(self):
 ...         print C4.x


 In statements outside the class:
 >>> class C3(object):
 ...     x = 23
 >>> C3.x = 42

J.M.Gimeno (jmgimeno@diei.udl.cat)      OOP in Python   Curs 2009-2010   9 / 49
Classes


Class-private attributes
        When a statement in the body (or in a method in the body) uses an
        identifier starting with two underscores (but not ending with them)
        such as private, the Python compiler changes it to
         classname private
        This lets classes to use private names reducing the risk of accidentally
        duplicating names used elsewhere
        By convention all identifiers starting with a single underscore are
        meant to be private in the scope that binds them

 >>> class C5(object):
 ...      private = 23
 >>> print C5.__private
 AttributeError: class A has no attribute ’ private’
 >>> print C5. C5 private
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python            Curs 2009-2010   10 / 49
Classes


Class-private attributes
        When a statement in the body (or in a method in the body) uses an
        identifier starting with two underscores (but not ending with them)
        such as private, the Python compiler changes it to
         classname private
        This lets classes to use private names reducing the risk of accidentally
        duplicating names used elsewhere
        By convention all identifiers starting with a single underscore are
        meant to be private in the scope that binds them

 >>> class C5(object):
 ...      private = 23
 >>> print C5.__private
 AttributeError: class A has no attribute ’ private’
 >>> print C5. C5 private
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python            Curs 2009-2010   10 / 49
Classes


Class-private attributes
        When a statement in the body (or in a method in the body) uses an
        identifier starting with two underscores (but not ending with them)
        such as private, the Python compiler changes it to
         classname private
        This lets classes to use private names reducing the risk of accidentally
        duplicating names used elsewhere
        By convention all identifiers starting with a single underscore are
        meant to be private in the scope that binds them

 >>> class C5(object):
 ...      private = 23
 >>> print C5.__private
 AttributeError: class A has no attribute ’ private’
 >>> print C5. C5 private
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python            Curs 2009-2010   10 / 49
Classes


Class-private attributes
        When a statement in the body (or in a method in the body) uses an
        identifier starting with two underscores (but not ending with them)
        such as private, the Python compiler changes it to
         classname private
        This lets classes to use private names reducing the risk of accidentally
        duplicating names used elsewhere
        By convention all identifiers starting with a single underscore are
        meant to be private in the scope that binds them

 >>> class C5(object):
 ...      private = 23
 >>> print C5.__private
 AttributeError: class A has no attribute ’ private’
 >>> print C5. C5 private
 23

J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python            Curs 2009-2010   10 / 49
Classes


Function definitions in a class body
       Most class bodies include def statements since functions (called methods in
       this context) are important attributes for most class objects
       A method defined in a class body has a mandatory first parameter
       (conventionally called self) that refers to the instance on which the method
       is called (staticmethods and classmethods are not considered now)
       A class can define a variety of special methods (two leading and two trailing
       underscores) relating to specific operation on its instances

 >>> class C5(object):
 ...     """This is the docstring of the class.
 ...     It can be accessed by C5. doc """
 ...     def hello(self):
 ...         "And this the docstring of the method"
 ...         print "Hello!!"




J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python               Curs 2009-2010   11 / 49
Classes


Function definitions in a class body
       Most class bodies include def statements since functions (called methods in
       this context) are important attributes for most class objects
       A method defined in a class body has a mandatory first parameter
       (conventionally called self) that refers to the instance on which the method
       is called (staticmethods and classmethods are not considered now)
       A class can define a variety of special methods (two leading and two trailing
       underscores) relating to specific operation on its instances

 >>> class C5(object):
 ...     """This is the docstring of the class.
 ...     It can be accessed by C5. doc """
 ...     def hello(self):
 ...         "And this the docstring of the method"
 ...         print "Hello!!"




J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python               Curs 2009-2010   11 / 49
Classes


Function definitions in a class body
       Most class bodies include def statements since functions (called methods in
       this context) are important attributes for most class objects
       A method defined in a class body has a mandatory first parameter
       (conventionally called self) that refers to the instance on which the method
       is called (staticmethods and classmethods are not considered now)
       A class can define a variety of special methods (two leading and two trailing
       underscores) relating to specific operation on its instances

 >>> class C5(object):
 ...     """This is the docstring of the class.
 ...     It can be accessed by C5. doc """
 ...     def hello(self):
 ...         "And this the docstring of the method"
 ...         print "Hello!!"




J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python               Curs 2009-2010   11 / 49
Classes


Function definitions in a class body
       Most class bodies include def statements since functions (called methods in
       this context) are important attributes for most class objects
       A method defined in a class body has a mandatory first parameter
       (conventionally called self) that refers to the instance on which the method
       is called (staticmethods and classmethods are not considered now)
       A class can define a variety of special methods (two leading and two trailing
       underscores) relating to specific operation on its instances

 >>> class C5(object):
 ...     """This is the docstring of the class.
 ...     It can be accessed by C5. doc """
 ...     def hello(self):
 ...         "And this the docstring of the method"
 ...         print "Hello!!"




J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python               Curs 2009-2010   11 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Creating Instances 1

       To create an instance of a      >>> anInstance = C5()
       class, call the class object as >>> isinstance(anInstance, C5)
       if it were a function           True
                                       >>> class C6(object):
       If it defines or inherits
                                       ...     def init (self, n):
         init , calling the class
                                       ...         self.x = n
       object implicitly calls it to
                                       >>> anInstance = C6(42)
       perform any needed
                                       >>> print anInstance.x
       instance-specific
                                       42
       initialisation
                                       >>> anInstance.z = 8
       You can give an instance an >>> print anInstance.z
       attribute by binding a value 8
       to an attribute reference


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   12 / 49
Instances I


Attributes of Instance Objects
 Attributes can be bound inside or outside class methods

  >>>   class C1(object):
                                                   >>>    class C2(object):
  ...       def amethod(self, n=8):
                                                   ...        pass
  ...            self.n = n
                                                   >>>    d = C2()
  >>>   c = C1()
                                                   >>>    d.n = 15
  >>>   c.amethod()
                                                   >>>    print d.n
  >>>   print c.n
                                                   15
  8

 Some attributes are implicitly set (both can be rebound but not unbound):

 >>> print d. class
 <class ’ main .C2’>
 >>> d. dict [’z’] = 42
 >>> print d.z
 42
 >>> print d. dict [’n’]
 15


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                  Curs 2009-2010   13 / 49
Instances I


Attributes of Instance Objects
 Attributes can be bound inside or outside class methods

  >>>   class C1(object):
                                                   >>>    class C2(object):
  ...       def amethod(self, n=8):
                                                   ...        pass
  ...            self.n = n
                                                   >>>    d = C2()
  >>>   c = C1()
                                                   >>>    d.n = 15
  >>>   c.amethod()
                                                   >>>    print d.n
  >>>   print c.n
                                                   15
  8

 Some attributes are implicitly set (both can be rebound but not unbound):

 >>> print d. class
 <class ’ main .C2’>
 >>> d. dict [’z’] = 42
 >>> print d.z
 42
 >>> print d. dict [’n’]
 15


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                  Curs 2009-2010   13 / 49
Instances I


Attributes of Instance Objects
 Attributes can be bound inside or outside class methods

  >>>   class C1(object):
                                                   >>>    class C2(object):
  ...       def amethod(self, n=8):
                                                   ...        pass
  ...            self.n = n
                                                   >>>    d = C2()
  >>>   c = C1()
                                                   >>>    d.n = 15
  >>>   c.amethod()
                                                   >>>    print d.n
  >>>   print c.n
                                                   15
  8

 Some attributes are implicitly set (both can be rebound but not unbound):

 >>> print d. class
 <class ’ main .C2’>
 >>> d. dict [’z’] = 42
 >>> print d.z
 42
 >>> print d. dict [’n’]
 15


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                  Curs 2009-2010   13 / 49
Instances I


Attributes of Instance Objects
 Attributes can be bound inside or outside class methods

  >>>   class C1(object):
                                                   >>>    class C2(object):
  ...       def amethod(self, n=8):
                                                   ...        pass
  ...            self.n = n
                                                   >>>    d = C2()
  >>>   c = C1()
                                                   >>>    d.n = 15
  >>>   c.amethod()
                                                   >>>    print d.n
  >>>   print c.n
                                                   15
  8

 Some attributes are implicitly set (both can be rebound but not unbound):

 >>> print d. class
 <class ’ main .C2’>
 >>> d. dict [’z’] = 42
 >>> print d.z
 42
 >>> print d. dict [’n’]
 15


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                  Curs 2009-2010   13 / 49
Instances I


Attributes of Instance Objects
 Attributes can be bound inside or outside class methods

  >>>   class C1(object):
                                                   >>>    class C2(object):
  ...       def amethod(self, n=8):
                                                   ...        pass
  ...            self.n = n
                                                   >>>    d = C2()
  >>>   c = C1()
                                                   >>>    d.n = 15
  >>>   c.amethod()
                                                   >>>    print d.n
  >>>   print c.n
                                                   15
  8

 Some attributes are implicitly set (both can be rebound but not unbound):

 >>> print d. class
 <class ’ main .C2’>
 >>> d. dict [’z’] = 42
 >>> print d.z
 42
 >>> print d. dict [’n’]
 15


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                  Curs 2009-2010   13 / 49
Instances I


Attributes of Instance Objects
 Attributes can be bound inside or outside class methods

  >>>   class C1(object):
                                                   >>>    class C2(object):
  ...       def amethod(self, n=8):
                                                   ...        pass
  ...            self.n = n
                                                   >>>    d = C2()
  >>>   c = C1()
                                                   >>>    d.n = 15
  >>>   c.amethod()
                                                   >>>    print d.n
  >>>   print c.n
                                                   15
  8

 Some attributes are implicitly set (both can be rebound but not unbound):

 >>> print d. class
 <class ’ main .C2’>
 >>> d. dict [’z’] = 42
 >>> print d.z
 42
 >>> print d. dict [’n’]
 15


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                  Curs 2009-2010   13 / 49
Instances I


Attributes of Instance Objects
 Attributes can be bound inside or outside class methods

  >>>   class C1(object):
                                                   >>>    class C2(object):
  ...       def amethod(self, n=8):
                                                   ...        pass
  ...            self.n = n
                                                   >>>    d = C2()
  >>>   c = C1()
                                                   >>>    d.n = 15
  >>>   c.amethod()
                                                   >>>    print d.n
  >>>   print c.n
                                                   15
  8

 Some attributes are implicitly set (both can be rebound but not unbound):

 >>> print d. class
 <class ’ main .C2’>
 >>> d. dict [’z’] = 42
 >>> print d.z
 42
 >>> print d. dict [’n’]
 15


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                  Curs 2009-2010   13 / 49
Descriptors


Descriptors

        A descriptor is any new-style object whose class supplies a special
        method named get
        Descriptors that are class attributes control the semantics of
        accessing and setting attributes on instances of that class
        If a descriptor’s class also supplies method set      then it is called an
        overriding descriptor (a.k.a. data descriptor)
        If not, it is called non-overriding (a.k.a. non-data) descriptor
        Function objects (and methods) are non-overriding descriptors
        Descriptors are the mechanism behind properties, methods, static
        methods, class methods, and super (cooperative super-classes)
        The descriptor protocol also contains method      delete      for
        unbinding attributes but it is seldom used


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python         Curs 2009-2010   14 / 49
Descriptors


Descriptors

        A descriptor is any new-style object whose class supplies a special
        method named get
        Descriptors that are class attributes control the semantics of
        accessing and setting attributes on instances of that class
        If a descriptor’s class also supplies method set      then it is called an
        overriding descriptor (a.k.a. data descriptor)
        If not, it is called non-overriding (a.k.a. non-data) descriptor
        Function objects (and methods) are non-overriding descriptors
        Descriptors are the mechanism behind properties, methods, static
        methods, class methods, and super (cooperative super-classes)
        The descriptor protocol also contains method      delete      for
        unbinding attributes but it is seldom used


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python         Curs 2009-2010   14 / 49
Descriptors


Descriptors

        A descriptor is any new-style object whose class supplies a special
        method named get
        Descriptors that are class attributes control the semantics of
        accessing and setting attributes on instances of that class
        If a descriptor’s class also supplies method set      then it is called an
        overriding descriptor (a.k.a. data descriptor)
        If not, it is called non-overriding (a.k.a. non-data) descriptor
        Function objects (and methods) are non-overriding descriptors
        Descriptors are the mechanism behind properties, methods, static
        methods, class methods, and super (cooperative super-classes)
        The descriptor protocol also contains method      delete      for
        unbinding attributes but it is seldom used


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python         Curs 2009-2010   14 / 49
Descriptors


Descriptors

        A descriptor is any new-style object whose class supplies a special
        method named get
        Descriptors that are class attributes control the semantics of
        accessing and setting attributes on instances of that class
        If a descriptor’s class also supplies method set      then it is called an
        overriding descriptor (a.k.a. data descriptor)
        If not, it is called non-overriding (a.k.a. non-data) descriptor
        Function objects (and methods) are non-overriding descriptors
        Descriptors are the mechanism behind properties, methods, static
        methods, class methods, and super (cooperative super-classes)
        The descriptor protocol also contains method      delete      for
        unbinding attributes but it is seldom used


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python         Curs 2009-2010   14 / 49
Descriptors


Descriptors

        A descriptor is any new-style object whose class supplies a special
        method named get
        Descriptors that are class attributes control the semantics of
        accessing and setting attributes on instances of that class
        If a descriptor’s class also supplies method set      then it is called an
        overriding descriptor (a.k.a. data descriptor)
        If not, it is called non-overriding (a.k.a. non-data) descriptor
        Function objects (and methods) are non-overriding descriptors
        Descriptors are the mechanism behind properties, methods, static
        methods, class methods, and super (cooperative super-classes)
        The descriptor protocol also contains method      delete      for
        unbinding attributes but it is seldom used


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python         Curs 2009-2010   14 / 49
Descriptors


Descriptors

        A descriptor is any new-style object whose class supplies a special
        method named get
        Descriptors that are class attributes control the semantics of
        accessing and setting attributes on instances of that class
        If a descriptor’s class also supplies method set      then it is called an
        overriding descriptor (a.k.a. data descriptor)
        If not, it is called non-overriding (a.k.a. non-data) descriptor
        Function objects (and methods) are non-overriding descriptors
        Descriptors are the mechanism behind properties, methods, static
        methods, class methods, and super (cooperative super-classes)
        The descriptor protocol also contains method      delete      for
        unbinding attributes but it is seldom used


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python         Curs 2009-2010   14 / 49
Descriptors


Descriptors

        A descriptor is any new-style object whose class supplies a special
        method named get
        Descriptors that are class attributes control the semantics of
        accessing and setting attributes on instances of that class
        If a descriptor’s class also supplies method set      then it is called an
        overriding descriptor (a.k.a. data descriptor)
        If not, it is called non-overriding (a.k.a. non-data) descriptor
        Function objects (and methods) are non-overriding descriptors
        Descriptors are the mechanism behind properties, methods, static
        methods, class methods, and super (cooperative super-classes)
        The descriptor protocol also contains method      delete      for
        unbinding attributes but it is seldom used


J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python         Curs 2009-2010   14 / 49
Descriptors


A Descriptor Example
 >>>    class Area(object):
 ...       """An overriding descriptor"""
 ...        def get (self, obj, klass):
 ...            return obj.x * obj.y
 ...        def set (self, obj, value):
 ...            raise AttributeError
 >>>    class Rectangle(object):
 ...        """A new-style class for representing rectangles"""
 ...        area = Area()
 ...        def init (self, x, y):
 ...            self.x = x
 ...            self.y = y
 >>>    r = Rectangle(5, 10)
 >>>    print r.area
 50

J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python   Curs 2009-2010   15 / 49
Descriptors   Referencing Attributes


Attribute Reference Basics


        An attribute reference is an expression of the form x.name, where x is
        an expression and name is an identifier
        Many kinds of Python objects have attributes, but an attribute
        reference when x refers to a class or an instance has special rich
        semantics
        The mechanics of attribute getting is defined in the special method
         getattribute
        The predefined behaviour is defined in the implementation of this
        method in the type (for class attributes) and object (for instance
        attributes) built-in types




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                     Curs 2009-2010   16 / 49
Descriptors   Referencing Attributes


Attribute Reference Basics


        An attribute reference is an expression of the form x.name, where x is
        an expression and name is an identifier
        Many kinds of Python objects have attributes, but an attribute
        reference when x refers to a class or an instance has special rich
        semantics
        The mechanics of attribute getting is defined in the special method
         getattribute
        The predefined behaviour is defined in the implementation of this
        method in the type (for class attributes) and object (for instance
        attributes) built-in types




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                     Curs 2009-2010   16 / 49
Descriptors   Referencing Attributes


Attribute Reference Basics


        An attribute reference is an expression of the form x.name, where x is
        an expression and name is an identifier
        Many kinds of Python objects have attributes, but an attribute
        reference when x refers to a class or an instance has special rich
        semantics
        The mechanics of attribute getting is defined in the special method
         getattribute
        The predefined behaviour is defined in the implementation of this
        method in the type (for class attributes) and object (for instance
        attributes) built-in types




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                     Curs 2009-2010   16 / 49
Descriptors   Referencing Attributes


Attribute Reference Basics


        An attribute reference is an expression of the form x.name, where x is
        an expression and name is an identifier
        Many kinds of Python objects have attributes, but an attribute
        reference when x refers to a class or an instance has special rich
        semantics
        The mechanics of attribute getting is defined in the special method
         getattribute
        The predefined behaviour is defined in the implementation of this
        method in the type (for class attributes) and object (for instance
        attributes) built-in types




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                     Curs 2009-2010   16 / 49
Descriptors   Referencing Attributes


Getting an attribute from a class


 When you use the syntax C.name to refer to an attribute on a class object
 C, the look-up proceeds in two steps:
   1 When ’name’ is a key in C. dict , C.name fetches the value v

      from C. dict [’name’].
               If v is a descriptor (i.e. type(v) supplies a            get   method), then
               type(v). get (v,None,C) is returned
               Otherwise, ir returns v
    2   Otherwise, it delegates the look-up to its base classes (in method
        resolution order)
 When these look-ups steps do not find an attribute, Python raises an
 AttributeError exception.




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                        Curs 2009-2010   17 / 49
Descriptors   Referencing Attributes


Getting an attribute from a class


 When you use the syntax C.name to refer to an attribute on a class object
 C, the look-up proceeds in two steps:
   1 When ’name’ is a key in C. dict , C.name fetches the value v

      from C. dict [’name’].
               If v is a descriptor (i.e. type(v) supplies a            get   method), then
               type(v). get (v,None,C) is returned
               Otherwise, ir returns v
    2   Otherwise, it delegates the look-up to its base classes (in method
        resolution order)
 When these look-ups steps do not find an attribute, Python raises an
 AttributeError exception.




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                        Curs 2009-2010   17 / 49
Descriptors   Referencing Attributes


Getting an attribute from a class


 When you use the syntax C.name to refer to an attribute on a class object
 C, the look-up proceeds in two steps:
   1 When ’name’ is a key in C. dict , C.name fetches the value v

      from C. dict [’name’].
               If v is a descriptor (i.e. type(v) supplies a            get   method), then
               type(v). get (v,None,C) is returned
               Otherwise, ir returns v
    2   Otherwise, it delegates the look-up to its base classes (in method
        resolution order)
 When these look-ups steps do not find an attribute, Python raises an
 AttributeError exception.




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                        Curs 2009-2010   17 / 49
Descriptors   Referencing Attributes


Getting an attribute from a class


 When you use the syntax C.name to refer to an attribute on a class object
 C, the look-up proceeds in two steps:
   1 When ’name’ is a key in C. dict , C.name fetches the value v

      from C. dict [’name’].
               If v is a descriptor (i.e. type(v) supplies a            get   method), then
               type(v). get (v,None,C) is returned
               Otherwise, ir returns v
    2   Otherwise, it delegates the look-up to its base classes (in method
        resolution order)
 When these look-ups steps do not find an attribute, Python raises an
 AttributeError exception.




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                        Curs 2009-2010   17 / 49
Descriptors   Referencing Attributes


Getting an attribute from a class


 When you use the syntax C.name to refer to an attribute on a class object
 C, the look-up proceeds in two steps:
   1 When ’name’ is a key in C. dict , C.name fetches the value v

      from C. dict [’name’].
               If v is a descriptor (i.e. type(v) supplies a            get   method), then
               type(v). get (v,None,C) is returned
               Otherwise, ir returns v
    2   Otherwise, it delegates the look-up to its base classes (in method
        resolution order)
 When these look-ups steps do not find an attribute, Python raises an
 AttributeError exception.




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                        Curs 2009-2010   17 / 49
Descriptors   Referencing Attributes


Getting an attribute from a class


 When you use the syntax C.name to refer to an attribute on a class object
 C, the look-up proceeds in two steps:
   1 When ’name’ is a key in C. dict , C.name fetches the value v

      from C. dict [’name’].
               If v is a descriptor (i.e. type(v) supplies a            get   method), then
               type(v). get (v,None,C) is returned
               Otherwise, ir returns v
    2   Otherwise, it delegates the look-up to its base classes (in method
        resolution order)
 When these look-ups steps do not find an attribute, Python raises an
 AttributeError exception.




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                        Curs 2009-2010   17 / 49
Descriptors   Referencing Attributes


Getting an attribute from a class


 When you use the syntax C.name to refer to an attribute on a class object
 C, the look-up proceeds in two steps:
   1 When ’name’ is a key in C. dict , C.name fetches the value v

      from C. dict [’name’].
               If v is a descriptor (i.e. type(v) supplies a            get   method), then
               type(v). get (v,None,C) is returned
               Otherwise, ir returns v
    2   Otherwise, it delegates the look-up to its base classes (in method
        resolution order)
 When these look-ups steps do not find an attribute, Python raises an
 AttributeError exception.




J.M.Gimeno (jmgimeno@diei.udl.cat)        OOP in Python                        Curs 2009-2010   17 / 49
Descriptors   Referencing Attributes


Getting an attribute from an instance I

 When you use the syntax x.name to refer to an attribute of instance x of
 class C, the look-up proceeds in three steps:
    1   When ’name’ is found in C (or in one of C’s ancestor classes) as the
        name of an overriding descriptor v (i.e. type(v) supplies both
         get and set ), then the value of x.name is
        type(v). get (v,x,C)
    2   Otherwise,      when ’name’ is key in x. dict , x.name fetches and
        returns x.       dict [’name’]
    3   Otherwise,      x.name delegates the look-up to x’s class (looking into
        C. dict         or delegating to C’s bases) and
               if a descriptor v is found, the overall result is again
               type(v). get (v,x,C).
               if a nondescriptor value v is found, the result is v.



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python                     Curs 2009-2010   18 / 49
Descriptors   Referencing Attributes


Getting an attribute from an instance I

 When you use the syntax x.name to refer to an attribute of instance x of
 class C, the look-up proceeds in three steps:
    1   When ’name’ is found in C (or in one of C’s ancestor classes) as the
        name of an overriding descriptor v (i.e. type(v) supplies both
         get and set ), then the value of x.name is
        type(v). get (v,x,C)
    2   Otherwise,      when ’name’ is key in x. dict , x.name fetches and
        returns x.       dict [’name’]
    3   Otherwise,      x.name delegates the look-up to x’s class (looking into
        C. dict         or delegating to C’s bases) and
               if a descriptor v is found, the overall result is again
               type(v). get (v,x,C).
               if a nondescriptor value v is found, the result is v.



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python                     Curs 2009-2010   18 / 49
Descriptors   Referencing Attributes


Getting an attribute from an instance I

 When you use the syntax x.name to refer to an attribute of instance x of
 class C, the look-up proceeds in three steps:
    1   When ’name’ is found in C (or in one of C’s ancestor classes) as the
        name of an overriding descriptor v (i.e. type(v) supplies both
         get and set ), then the value of x.name is
        type(v). get (v,x,C)
    2   Otherwise,      when ’name’ is key in x. dict , x.name fetches and
        returns x.       dict [’name’]
    3   Otherwise,      x.name delegates the look-up to x’s class (looking into
        C. dict         or delegating to C’s bases) and
               if a descriptor v is found, the overall result is again
               type(v). get (v,x,C).
               if a nondescriptor value v is found, the result is v.



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python                     Curs 2009-2010   18 / 49
Descriptors   Referencing Attributes


Getting an attribute from an instance I

 When you use the syntax x.name to refer to an attribute of instance x of
 class C, the look-up proceeds in three steps:
    1   When ’name’ is found in C (or in one of C’s ancestor classes) as the
        name of an overriding descriptor v (i.e. type(v) supplies both
         get and set ), then the value of x.name is
        type(v). get (v,x,C)
    2   Otherwise,      when ’name’ is key in x. dict , x.name fetches and
        returns x.       dict [’name’]
    3   Otherwise,      x.name delegates the look-up to x’s class (looking into
        C. dict         or delegating to C’s bases) and
               if a descriptor v is found, the overall result is again
               type(v). get (v,x,C).
               if a nondescriptor value v is found, the result is v.



J.M.Gimeno (jmgimeno@diei.udl.cat)         OOP in Python                     Curs 2009-2010   18 / 49
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python
Object Oriented Programming in Python

Weitere ähnliche Inhalte

Was ist angesagt?

Ontology Integration and Interoperability (OntoIOp) – Part 1: The Distributed...
Ontology Integration and Interoperability (OntoIOp) – Part 1: The Distributed...Ontology Integration and Interoperability (OntoIOp) – Part 1: The Distributed...
Ontology Integration and Interoperability (OntoIOp) – Part 1: The Distributed...Christoph Lange
 
Object Oriented Approach Within Siebel Boundaries
Object Oriented Approach Within Siebel BoundariesObject Oriented Approach Within Siebel Boundaries
Object Oriented Approach Within Siebel BoundariesRoman Agaev
 
Propelling Standards-based Sharing and Reuse in Instructional Modeling Commun...
Propelling Standards-based Sharing and Reuse in Instructional Modeling Commun...Propelling Standards-based Sharing and Reuse in Instructional Modeling Commun...
Propelling Standards-based Sharing and Reuse in Instructional Modeling Commun...Michael Derntl
 
Pal gov.tutorial4.session1 1.needforsharedsemantics
Pal gov.tutorial4.session1 1.needforsharedsemanticsPal gov.tutorial4.session1 1.needforsharedsemantics
Pal gov.tutorial4.session1 1.needforsharedsemanticsMustafa Jarrar
 
Natural language processing using python
Natural language processing using pythonNatural language processing using python
Natural language processing using pythonPrakash Anand
 
IRJET- Survey on Generating Suggestions for Erroneous Part in a Sentence
IRJET- Survey on Generating Suggestions for Erroneous Part in a SentenceIRJET- Survey on Generating Suggestions for Erroneous Part in a Sentence
IRJET- Survey on Generating Suggestions for Erroneous Part in a SentenceIRJET Journal
 
Extractive Summarization with Very Deep Pretrained Language Model
Extractive Summarization with Very Deep Pretrained Language ModelExtractive Summarization with Very Deep Pretrained Language Model
Extractive Summarization with Very Deep Pretrained Language Modelgerogepatton
 
Pal gov.tutorial4.outline
Pal gov.tutorial4.outlinePal gov.tutorial4.outline
Pal gov.tutorial4.outlineMustafa Jarrar
 
Modeling of Speech Synthesis of Standard Arabic Using an Expert System
Modeling of Speech Synthesis of Standard Arabic Using an Expert SystemModeling of Speech Synthesis of Standard Arabic Using an Expert System
Modeling of Speech Synthesis of Standard Arabic Using an Expert Systemcsandit
 
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCEDETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCEAbdurrahimDerric
 

Was ist angesagt? (16)

Ontology Integration and Interoperability (OntoIOp) – Part 1: The Distributed...
Ontology Integration and Interoperability (OntoIOp) – Part 1: The Distributed...Ontology Integration and Interoperability (OntoIOp) – Part 1: The Distributed...
Ontology Integration and Interoperability (OntoIOp) – Part 1: The Distributed...
 
Object Oriented Approach Within Siebel Boundaries
Object Oriented Approach Within Siebel BoundariesObject Oriented Approach Within Siebel Boundaries
Object Oriented Approach Within Siebel Boundaries
 
10.1.1.35.8376
10.1.1.35.837610.1.1.35.8376
10.1.1.35.8376
 
Propelling Standards-based Sharing and Reuse in Instructional Modeling Commun...
Propelling Standards-based Sharing and Reuse in Instructional Modeling Commun...Propelling Standards-based Sharing and Reuse in Instructional Modeling Commun...
Propelling Standards-based Sharing and Reuse in Instructional Modeling Commun...
 
Pal gov.tutorial4.session1 1.needforsharedsemantics
Pal gov.tutorial4.session1 1.needforsharedsemanticsPal gov.tutorial4.session1 1.needforsharedsemantics
Pal gov.tutorial4.session1 1.needforsharedsemantics
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Natural language processing using python
Natural language processing using pythonNatural language processing using python
Natural language processing using python
 
Icsme16.ppt
Icsme16.pptIcsme16.ppt
Icsme16.ppt
 
IRJET- Survey on Generating Suggestions for Erroneous Part in a Sentence
IRJET- Survey on Generating Suggestions for Erroneous Part in a SentenceIRJET- Survey on Generating Suggestions for Erroneous Part in a Sentence
IRJET- Survey on Generating Suggestions for Erroneous Part in a Sentence
 
Extractive Summarization with Very Deep Pretrained Language Model
Extractive Summarization with Very Deep Pretrained Language ModelExtractive Summarization with Very Deep Pretrained Language Model
Extractive Summarization with Very Deep Pretrained Language Model
 
Pal gov.tutorial4.outline
Pal gov.tutorial4.outlinePal gov.tutorial4.outline
Pal gov.tutorial4.outline
 
Modeling of Speech Synthesis of Standard Arabic Using an Expert System
Modeling of Speech Synthesis of Standard Arabic Using an Expert SystemModeling of Speech Synthesis of Standard Arabic Using an Expert System
Modeling of Speech Synthesis of Standard Arabic Using an Expert System
 
Csci360 20 (1)
Csci360 20 (1)Csci360 20 (1)
Csci360 20 (1)
 
Csci360 20
Csci360 20Csci360 20
Csci360 20
 
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCEDETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
DETERMINING CUSTOMER SATISFACTION IN-ECOMMERCE
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 

Andere mochten auch

Powerpoint de maría bayo martínez hcyt
Powerpoint de maría bayo martínez hcytPowerpoint de maría bayo martínez hcyt
Powerpoint de maría bayo martínez hcytMaría Bayo Martínez
 
MacPherson Group Presentation
MacPherson Group PresentationMacPherson Group Presentation
MacPherson Group Presentationangelodanielrossi
 
Sistema de Salud en el Peru
Sistema de Salud en el Peru  Sistema de Salud en el Peru
Sistema de Salud en el Peru UNMSM
 

Andere mochten auch (8)

Powerpoint de maría bayo martínez hcyt
Powerpoint de maría bayo martínez hcytPowerpoint de maría bayo martínez hcyt
Powerpoint de maría bayo martínez hcyt
 
MacPherson Group Presentation
MacPherson Group PresentationMacPherson Group Presentation
MacPherson Group Presentation
 
CQ Personnel Presentation
CQ Personnel PresentationCQ Personnel Presentation
CQ Personnel Presentation
 
Hostel lyf new
Hostel lyf newHostel lyf new
Hostel lyf new
 
CQ/VMS Global Presentation
CQ/VMS Global PresentationCQ/VMS Global Presentation
CQ/VMS Global Presentation
 
Back Bay Staffing Group
Back Bay Staffing GroupBack Bay Staffing Group
Back Bay Staffing Group
 
Sistema de Salud en el Peru
Sistema de Salud en el Peru  Sistema de Salud en el Peru
Sistema de Salud en el Peru
 
Linear programming
Linear programmingLinear programming
Linear programming
 

Ähnlich wie Object Oriented Programming in Python

Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in PythonJuan-Manuel Gimeno
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in pythonnitamhaske
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4Binay Kumar Ray
 
Using at least two examples (whenever applicable), concisely discuss .pdf
Using at least two examples (whenever applicable), concisely discuss .pdfUsing at least two examples (whenever applicable), concisely discuss .pdf
Using at least two examples (whenever applicable), concisely discuss .pdfrajeshjangid1865
 
Python-Mastering-the-Language-of-Data-Science.pptx
Python-Mastering-the-Language-of-Data-Science.pptxPython-Mastering-the-Language-of-Data-Science.pptx
Python-Mastering-the-Language-of-Data-Science.pptxdmdHaneef
 
1 intro
1 intro1 intro
1 introabha48
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 
lec(1).pptx
lec(1).pptxlec(1).pptx
lec(1).pptxMemMem25
 
PHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptxPHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptxAtikur Rahman
 
Object Oriented Programming Overview for the PeopleSoft Developer
Object Oriented Programming Overview for the PeopleSoft DeveloperObject Oriented Programming Overview for the PeopleSoft Developer
Object Oriented Programming Overview for the PeopleSoft DeveloperLee Greffin
 
Summer Training Project On Python Programming
Summer Training Project On Python ProgrammingSummer Training Project On Python Programming
Summer Training Project On Python ProgrammingKAUSHAL KUMAR JHA
 

Ähnlich wie Object Oriented Programming in Python (20)

Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in Python
 
chapter - 1.ppt
chapter - 1.pptchapter - 1.ppt
chapter - 1.ppt
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4
 
Using at least two examples (whenever applicable), concisely discuss .pdf
Using at least two examples (whenever applicable), concisely discuss .pdfUsing at least two examples (whenever applicable), concisely discuss .pdf
Using at least two examples (whenever applicable), concisely discuss .pdf
 
Python-Classes.pptx
Python-Classes.pptxPython-Classes.pptx
Python-Classes.pptx
 
Python-Mastering-the-Language-of-Data-Science.pptx
Python-Mastering-the-Language-of-Data-Science.pptxPython-Mastering-the-Language-of-Data-Science.pptx
Python-Mastering-the-Language-of-Data-Science.pptx
 
1 intro
1 intro1 intro
1 intro
 
PYTHON PPT.pptx
PYTHON PPT.pptxPYTHON PPT.pptx
PYTHON PPT.pptx
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
lec(1).pptx
lec(1).pptxlec(1).pptx
lec(1).pptx
 
OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
 
Chapter 1.pptx
Chapter 1.pptxChapter 1.pptx
Chapter 1.pptx
 
PHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptxPHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptx
 
Unit 1 OOSE
Unit 1 OOSE Unit 1 OOSE
Unit 1 OOSE
 
Object Oriented Programming Overview for the PeopleSoft Developer
Object Oriented Programming Overview for the PeopleSoft DeveloperObject Oriented Programming Overview for the PeopleSoft Developer
Object Oriented Programming Overview for the PeopleSoft Developer
 
Summer Training Project On Python Programming
Summer Training Project On Python ProgrammingSummer Training Project On Python Programming
Summer Training Project On Python Programming
 
Unit 5.ppt
Unit 5.pptUnit 5.ppt
Unit 5.ppt
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 

Kürzlich hochgeladen

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
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 ...apidays
 
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 TerraformAndrey Devyatkin
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
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.pdfOrbitshub
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
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].pdfOverkill Security
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
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 2024The Digital Insurer
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
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...DianaGray10
 
"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 ...Zilliz
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
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...Martijn de Jong
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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 ...
 
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
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
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...
 
"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 ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

Object Oriented Programming in Python

  • 1. Object Oriented Programming in Python Juan Manuel Gimeno Illa jmgimeno@diei.udl.cat Curs 2009-2010 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 1 / 49
  • 2. Outline 1 Introduction 2 Classes 3 Instances I 4 Descriptors Referencing Attributes Bound and Unbound Methods Properties Class-Level Methods 5 Inheritance Method Resolution Order Cooperative Superclasses 6 Instances II J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 2 / 49
  • 3. Introduction Programming Paradigms A programming paradigm consists in the basic concepts into which our programs are made of Procedural Modules, data structures and procedures that operate upon them Objectural Objects which encapsulate state and behaviour and messages passed between these objects Functional Functions and closures, recursion, lists, ... Python is a multiparadigm programming language this allows the programmer to choose the paradigm that best suits the problem this allows the program to mix paradigms this allows the program to evolve switching paradigm if necessary J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 3 / 49
  • 4. Introduction Programming Paradigms A programming paradigm consists in the basic concepts into which our programs are made of Procedural Modules, data structures and procedures that operate upon them Objectural Objects which encapsulate state and behaviour and messages passed between these objects Functional Functions and closures, recursion, lists, ... Python is a multiparadigm programming language this allows the programmer to choose the paradigm that best suits the problem this allows the program to mix paradigms this allows the program to evolve switching paradigm if necessary J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 3 / 49
  • 5. Introduction Programming Paradigms A programming paradigm consists in the basic concepts into which our programs are made of Procedural Modules, data structures and procedures that operate upon them Objectural Objects which encapsulate state and behaviour and messages passed between these objects Functional Functions and closures, recursion, lists, ... Python is a multiparadigm programming language this allows the programmer to choose the paradigm that best suits the problem this allows the program to mix paradigms this allows the program to evolve switching paradigm if necessary J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 3 / 49
  • 6. Introduction Programming Paradigms A programming paradigm consists in the basic concepts into which our programs are made of Procedural Modules, data structures and procedures that operate upon them Objectural Objects which encapsulate state and behaviour and messages passed between these objects Functional Functions and closures, recursion, lists, ... Python is a multiparadigm programming language this allows the programmer to choose the paradigm that best suits the problem this allows the program to mix paradigms this allows the program to evolve switching paradigm if necessary J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 3 / 49
  • 7. Introduction Programming Paradigms A programming paradigm consists in the basic concepts into which our programs are made of Procedural Modules, data structures and procedures that operate upon them Objectural Objects which encapsulate state and behaviour and messages passed between these objects Functional Functions and closures, recursion, lists, ... Python is a multiparadigm programming language this allows the programmer to choose the paradigm that best suits the problem this allows the program to mix paradigms this allows the program to evolve switching paradigm if necessary J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 3 / 49
  • 8. Introduction Programming Paradigms A programming paradigm consists in the basic concepts into which our programs are made of Procedural Modules, data structures and procedures that operate upon them Objectural Objects which encapsulate state and behaviour and messages passed between these objects Functional Functions and closures, recursion, lists, ... Python is a multiparadigm programming language this allows the programmer to choose the paradigm that best suits the problem this allows the program to mix paradigms this allows the program to evolve switching paradigm if necessary J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 3 / 49
  • 9. Introduction Programming Paradigms A programming paradigm consists in the basic concepts into which our programs are made of Procedural Modules, data structures and procedures that operate upon them Objectural Objects which encapsulate state and behaviour and messages passed between these objects Functional Functions and closures, recursion, lists, ... Python is a multiparadigm programming language this allows the programmer to choose the paradigm that best suits the problem this allows the program to mix paradigms this allows the program to evolve switching paradigm if necessary J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 3 / 49
  • 10. Introduction Programming Paradigms A programming paradigm consists in the basic concepts into which our programs are made of Procedural Modules, data structures and procedures that operate upon them Objectural Objects which encapsulate state and behaviour and messages passed between these objects Functional Functions and closures, recursion, lists, ... Python is a multiparadigm programming language this allows the programmer to choose the paradigm that best suits the problem this allows the program to mix paradigms this allows the program to evolve switching paradigm if necessary J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 3 / 49
  • 11. Classes Python classes A class is a python object with several characteristics: You can call a class as it where a function and this call returns a new instance of the class A class has arbitrary named attributes that can be bound, unbound an referenced The class attributes can be descriptors (including functions) or normal data objects Class attributes bound to functions are also known as methods A method can have special python-defined meaning (they’re named with two leading and trailing underscores) A class clan inherit from other classes, meaning it delegates to other classes the look-up of attributes that are not found in the class itself J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 4 / 49
  • 12. Classes Python classes A class is a python object with several characteristics: You can call a class as it where a function and this call returns a new instance of the class A class has arbitrary named attributes that can be bound, unbound an referenced The class attributes can be descriptors (including functions) or normal data objects Class attributes bound to functions are also known as methods A method can have special python-defined meaning (they’re named with two leading and trailing underscores) A class clan inherit from other classes, meaning it delegates to other classes the look-up of attributes that are not found in the class itself J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 4 / 49
  • 13. Classes Python classes A class is a python object with several characteristics: You can call a class as it where a function and this call returns a new instance of the class A class has arbitrary named attributes that can be bound, unbound an referenced The class attributes can be descriptors (including functions) or normal data objects Class attributes bound to functions are also known as methods A method can have special python-defined meaning (they’re named with two leading and trailing underscores) A class clan inherit from other classes, meaning it delegates to other classes the look-up of attributes that are not found in the class itself J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 4 / 49
  • 14. Classes Python classes A class is a python object with several characteristics: You can call a class as it where a function and this call returns a new instance of the class A class has arbitrary named attributes that can be bound, unbound an referenced The class attributes can be descriptors (including functions) or normal data objects Class attributes bound to functions are also known as methods A method can have special python-defined meaning (they’re named with two leading and trailing underscores) A class clan inherit from other classes, meaning it delegates to other classes the look-up of attributes that are not found in the class itself J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 4 / 49
  • 15. Classes Python classes A class is a python object with several characteristics: You can call a class as it where a function and this call returns a new instance of the class A class has arbitrary named attributes that can be bound, unbound an referenced The class attributes can be descriptors (including functions) or normal data objects Class attributes bound to functions are also known as methods A method can have special python-defined meaning (they’re named with two leading and trailing underscores) A class clan inherit from other classes, meaning it delegates to other classes the look-up of attributes that are not found in the class itself J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 4 / 49
  • 16. Classes Python classes A class is a python object with several characteristics: You can call a class as it where a function and this call returns a new instance of the class A class has arbitrary named attributes that can be bound, unbound an referenced The class attributes can be descriptors (including functions) or normal data objects Class attributes bound to functions are also known as methods A method can have special python-defined meaning (they’re named with two leading and trailing underscores) A class clan inherit from other classes, meaning it delegates to other classes the look-up of attributes that are not found in the class itself J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 4 / 49
  • 17. Classes Object models Since Python2.2 there co-exist two slightly different object models in the language Old-style (classic) classes This is the model existing prior to Python2.2 New-style classes This is the preferred model for new code Old-style New-style >>> class A: pass >>> class A(object): pass >>> class B: pass >>> class B(object): pass >>> a, b = A(), B() >>> a, b = A(), B() >>> type(a) == type(b) >>> type(a) == type(b) True False >>> type(a) >>> type(a) <type ’instance’> <class ’ main .A’> J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 5 / 49
  • 18. Classes Object models Since Python2.2 there co-exist two slightly different object models in the language Old-style (classic) classes This is the model existing prior to Python2.2 New-style classes This is the preferred model for new code Old-style New-style >>> class A: pass >>> class A(object): pass >>> class B: pass >>> class B(object): pass >>> a, b = A(), B() >>> a, b = A(), B() >>> type(a) == type(b) >>> type(a) == type(b) True False >>> type(a) >>> type(a) <type ’instance’> <class ’ main .A’> J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 5 / 49
  • 19. Classes Object models Since Python2.2 there co-exist two slightly different object models in the language Old-style (classic) classes This is the model existing prior to Python2.2 New-style classes This is the preferred model for new code Old-style New-style >>> class A: pass >>> class A(object): pass >>> class B: pass >>> class B(object): pass >>> a, b = A(), B() >>> a, b = A(), B() >>> type(a) == type(b) >>> type(a) == type(b) True False >>> type(a) >>> type(a) <type ’instance’> <class ’ main .A’> J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 5 / 49
  • 20. Classes Object models Since Python2.2 there co-exist two slightly different object models in the language Old-style (classic) classes This is the model existing prior to Python2.2 New-style classes This is the preferred model for new code Old-style New-style >>> class A: pass >>> class A(object): pass >>> class B: pass >>> class B(object): pass >>> a, b = A(), B() >>> a, b = A(), B() >>> type(a) == type(b) >>> type(a) == type(b) True False >>> type(a) >>> type(a) <type ’instance’> <class ’ main .A’> J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 5 / 49
  • 21. Classes Object models Since Python2.2 there co-exist two slightly different object models in the language Old-style (classic) classes This is the model existing prior to Python2.2 New-style classes This is the preferred model for new code Old-style New-style >>> class A: pass >>> class A(object): pass >>> class B: pass >>> class B(object): pass >>> a, b = A(), B() >>> a, b = A(), B() >>> type(a) == type(b) >>> type(a) == type(b) True False >>> type(a) >>> type(a) <type ’instance’> <class ’ main .A’> J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 5 / 49
  • 22. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 23. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 24. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 25. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 26. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 27. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 28. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 29. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 30. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 31. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 32. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 33. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 34. Classes New-style classes Defined in the type and class unification effort in python2.2 (Introduced without breaking backwards compatibility) Simpler, more regular and more powerful Built-in types (e.g. dict) can be subclassed Properties: attributes managed by get/set methods Static and class methods (via descriptor API) Cooperative classes (sane multiple inheritance) Meta-class programming It will be the default (and unique) in the future Documents: Unifying types and classes in Python 2.2 PEP-252: Making types look more like classes PEP-253: Subtyping built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 6 / 49
  • 35. Classes The class statement class classname(base-classes): statement(s) classname is a variable that gets (re)bound to the class object after the class statement finishes executing base-classes is a comma separated series of expressions whose values must be classes if it does not exists, the created class is old-style if all base-classes are old-style, the created class is old-style otherwise it is a new-style class1 since every type subclasses built-in object, we can use object to mark a class as new-style when no true bases exist The statements (a.k.a. the class body) define the set of class attributes which will be shared by all instances of the class 1 We are not considering metaclass now J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 7 / 49
  • 36. Classes The class statement class classname(base-classes): statement(s) classname is a variable that gets (re)bound to the class object after the class statement finishes executing base-classes is a comma separated series of expressions whose values must be classes if it does not exists, the created class is old-style if all base-classes are old-style, the created class is old-style otherwise it is a new-style class1 since every type subclasses built-in object, we can use object to mark a class as new-style when no true bases exist The statements (a.k.a. the class body) define the set of class attributes which will be shared by all instances of the class 1 We are not considering metaclass now J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 7 / 49
  • 37. Classes The class statement class classname(base-classes): statement(s) classname is a variable that gets (re)bound to the class object after the class statement finishes executing base-classes is a comma separated series of expressions whose values must be classes if it does not exists, the created class is old-style if all base-classes are old-style, the created class is old-style otherwise it is a new-style class1 since every type subclasses built-in object, we can use object to mark a class as new-style when no true bases exist The statements (a.k.a. the class body) define the set of class attributes which will be shared by all instances of the class 1 We are not considering metaclass now J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 7 / 49
  • 38. Classes The class statement class classname(base-classes): statement(s) classname is a variable that gets (re)bound to the class object after the class statement finishes executing base-classes is a comma separated series of expressions whose values must be classes if it does not exists, the created class is old-style if all base-classes are old-style, the created class is old-style otherwise it is a new-style class1 since every type subclasses built-in object, we can use object to mark a class as new-style when no true bases exist The statements (a.k.a. the class body) define the set of class attributes which will be shared by all instances of the class 1 We are not considering metaclass now J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 7 / 49
  • 39. Classes The class statement class classname(base-classes): statement(s) classname is a variable that gets (re)bound to the class object after the class statement finishes executing base-classes is a comma separated series of expressions whose values must be classes if it does not exists, the created class is old-style if all base-classes are old-style, the created class is old-style otherwise it is a new-style class1 since every type subclasses built-in object, we can use object to mark a class as new-style when no true bases exist The statements (a.k.a. the class body) define the set of class attributes which will be shared by all instances of the class 1 We are not considering metaclass now J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 7 / 49
  • 40. Classes The class statement class classname(base-classes): statement(s) classname is a variable that gets (re)bound to the class object after the class statement finishes executing base-classes is a comma separated series of expressions whose values must be classes if it does not exists, the created class is old-style if all base-classes are old-style, the created class is old-style otherwise it is a new-style class1 since every type subclasses built-in object, we can use object to mark a class as new-style when no true bases exist The statements (a.k.a. the class body) define the set of class attributes which will be shared by all instances of the class 1 We are not considering metaclass now J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 7 / 49
  • 41. Classes The class statement class classname(base-classes): statement(s) classname is a variable that gets (re)bound to the class object after the class statement finishes executing base-classes is a comma separated series of expressions whose values must be classes if it does not exists, the created class is old-style if all base-classes are old-style, the created class is old-style otherwise it is a new-style class1 since every type subclasses built-in object, we can use object to mark a class as new-style when no true bases exist The statements (a.k.a. the class body) define the set of class attributes which will be shared by all instances of the class 1 We are not considering metaclass now J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 7 / 49
  • 42. Classes The class statement class classname(base-classes): statement(s) classname is a variable that gets (re)bound to the class object after the class statement finishes executing base-classes is a comma separated series of expressions whose values must be classes if it does not exists, the created class is old-style if all base-classes are old-style, the created class is old-style otherwise it is a new-style class1 since every type subclasses built-in object, we can use object to mark a class as new-style when no true bases exist The statements (a.k.a. the class body) define the set of class attributes which will be shared by all instances of the class 1 We are not considering metaclass now J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 7 / 49
  • 43. Classes Attributes of class objects Attributes can be bound inside or outside the class body. >>> class C1(object): >>> class C2(object): pass ... x = 23 >>> C2.x = 23 >>> print C1.x >>> print C2.x 23 23 Some attributes are implicitly set: >>> print C1. name , C1. bases C1, (<type ’object’>,) >>> C1. dict [’z’] = 42 >>> print C1.z 42 >>> print C1. dict [’x’] 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 8 / 49
  • 44. Classes Attributes of class objects Attributes can be bound inside or outside the class body. >>> class C1(object): >>> class C2(object): pass ... x = 23 >>> C2.x = 23 >>> print C1.x >>> print C2.x 23 23 Some attributes are implicitly set: >>> print C1. name , C1. bases C1, (<type ’object’>,) >>> C1. dict [’z’] = 42 >>> print C1.z 42 >>> print C1. dict [’x’] 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 8 / 49
  • 45. Classes Attributes of class objects Attributes can be bound inside or outside the class body. >>> class C1(object): >>> class C2(object): pass ... x = 23 >>> C2.x = 23 >>> print C1.x >>> print C2.x 23 23 Some attributes are implicitly set: >>> print C1. name , C1. bases C1, (<type ’object’>,) >>> C1. dict [’z’] = 42 >>> print C1.z 42 >>> print C1. dict [’x’] 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 8 / 49
  • 46. Classes Attributes of class objects Attributes can be bound inside or outside the class body. >>> class C1(object): >>> class C2(object): pass ... x = 23 >>> C2.x = 23 >>> print C1.x >>> print C2.x 23 23 Some attributes are implicitly set: >>> print C1. name , C1. bases C1, (<type ’object’>,) >>> C1. dict [’z’] = 42 >>> print C1.z 42 >>> print C1. dict [’x’] 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 8 / 49
  • 47. Classes Attributes of class objects Attributes can be bound inside or outside the class body. >>> class C1(object): >>> class C2(object): pass ... x = 23 >>> C2.x = 23 >>> print C1.x >>> print C2.x 23 23 Some attributes are implicitly set: >>> print C1. name , C1. bases C1, (<type ’object’>,) >>> C1. dict [’z’] = 42 >>> print C1.z 42 >>> print C1. dict [’x’] 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 8 / 49
  • 48. Classes Attributes of class objects Attributes can be bound inside or outside the class body. >>> class C1(object): >>> class C2(object): pass ... x = 23 >>> C2.x = 23 >>> print C1.x >>> print C2.x 23 23 Some attributes are implicitly set: >>> print C1. name , C1. bases C1, (<type ’object’>,) >>> C1. dict [’z’] = 42 >>> print C1.z 42 >>> print C1. dict [’x’] 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 8 / 49
  • 49. Classes Attributes of class objects Attributes can be bound inside or outside the class body. >>> class C1(object): >>> class C2(object): pass ... x = 23 >>> C2.x = 23 >>> print C1.x >>> print C2.x 23 23 Some attributes are implicitly set: >>> print C1. name , C1. bases C1, (<type ’object’>,) >>> C1. dict [’z’] = 42 >>> print C1.z 42 >>> print C1. dict [’x’] 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 8 / 49
  • 50. Classes Accessing class attributes In statements directly inside the class’ body: >>> class C3(object): ... x = 23 ... y = x + 19 In statements in methods of the class: >>> class C4(object): ... x = 23 ... def amethod(self): ... print C4.x In statements outside the class: >>> class C3(object): ... x = 23 >>> C3.x = 42 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 9 / 49
  • 51. Classes Accessing class attributes In statements directly inside the class’ body: >>> class C3(object): ... x = 23 ... y = x + 19 In statements in methods of the class: >>> class C4(object): ... x = 23 ... def amethod(self): ... print C4.x In statements outside the class: >>> class C3(object): ... x = 23 >>> C3.x = 42 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 9 / 49
  • 52. Classes Accessing class attributes In statements directly inside the class’ body: >>> class C3(object): ... x = 23 ... y = x + 19 In statements in methods of the class: >>> class C4(object): ... x = 23 ... def amethod(self): ... print C4.x In statements outside the class: >>> class C3(object): ... x = 23 >>> C3.x = 42 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 9 / 49
  • 53. Classes Accessing class attributes In statements directly inside the class’ body: >>> class C3(object): ... x = 23 ... y = x + 19 In statements in methods of the class: >>> class C4(object): ... x = 23 ... def amethod(self): ... print C4.x In statements outside the class: >>> class C3(object): ... x = 23 >>> C3.x = 42 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 9 / 49
  • 54. Classes Accessing class attributes In statements directly inside the class’ body: >>> class C3(object): ... x = 23 ... y = x + 19 In statements in methods of the class: >>> class C4(object): ... x = 23 ... def amethod(self): ... print C4.x In statements outside the class: >>> class C3(object): ... x = 23 >>> C3.x = 42 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 9 / 49
  • 55. Classes Accessing class attributes In statements directly inside the class’ body: >>> class C3(object): ... x = 23 ... y = x + 19 In statements in methods of the class: >>> class C4(object): ... x = 23 ... def amethod(self): ... print C4.x In statements outside the class: >>> class C3(object): ... x = 23 >>> C3.x = 42 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 9 / 49
  • 56. Classes Accessing class attributes In statements directly inside the class’ body: >>> class C3(object): ... x = 23 ... y = x + 19 In statements in methods of the class: >>> class C4(object): ... x = 23 ... def amethod(self): ... print C4.x In statements outside the class: >>> class C3(object): ... x = 23 >>> C3.x = 42 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 9 / 49
  • 57. Classes Accessing class attributes In statements directly inside the class’ body: >>> class C3(object): ... x = 23 ... y = x + 19 In statements in methods of the class: >>> class C4(object): ... x = 23 ... def amethod(self): ... print C4.x In statements outside the class: >>> class C3(object): ... x = 23 >>> C3.x = 42 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 9 / 49
  • 58. Classes Accessing class attributes In statements directly inside the class’ body: >>> class C3(object): ... x = 23 ... y = x + 19 In statements in methods of the class: >>> class C4(object): ... x = 23 ... def amethod(self): ... print C4.x In statements outside the class: >>> class C3(object): ... x = 23 >>> C3.x = 42 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 9 / 49
  • 59. Classes Class-private attributes When a statement in the body (or in a method in the body) uses an identifier starting with two underscores (but not ending with them) such as private, the Python compiler changes it to classname private This lets classes to use private names reducing the risk of accidentally duplicating names used elsewhere By convention all identifiers starting with a single underscore are meant to be private in the scope that binds them >>> class C5(object): ... private = 23 >>> print C5.__private AttributeError: class A has no attribute ’ private’ >>> print C5. C5 private 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 10 / 49
  • 60. Classes Class-private attributes When a statement in the body (or in a method in the body) uses an identifier starting with two underscores (but not ending with them) such as private, the Python compiler changes it to classname private This lets classes to use private names reducing the risk of accidentally duplicating names used elsewhere By convention all identifiers starting with a single underscore are meant to be private in the scope that binds them >>> class C5(object): ... private = 23 >>> print C5.__private AttributeError: class A has no attribute ’ private’ >>> print C5. C5 private 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 10 / 49
  • 61. Classes Class-private attributes When a statement in the body (or in a method in the body) uses an identifier starting with two underscores (but not ending with them) such as private, the Python compiler changes it to classname private This lets classes to use private names reducing the risk of accidentally duplicating names used elsewhere By convention all identifiers starting with a single underscore are meant to be private in the scope that binds them >>> class C5(object): ... private = 23 >>> print C5.__private AttributeError: class A has no attribute ’ private’ >>> print C5. C5 private 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 10 / 49
  • 62. Classes Class-private attributes When a statement in the body (or in a method in the body) uses an identifier starting with two underscores (but not ending with them) such as private, the Python compiler changes it to classname private This lets classes to use private names reducing the risk of accidentally duplicating names used elsewhere By convention all identifiers starting with a single underscore are meant to be private in the scope that binds them >>> class C5(object): ... private = 23 >>> print C5.__private AttributeError: class A has no attribute ’ private’ >>> print C5. C5 private 23 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 10 / 49
  • 63. Classes Function definitions in a class body Most class bodies include def statements since functions (called methods in this context) are important attributes for most class objects A method defined in a class body has a mandatory first parameter (conventionally called self) that refers to the instance on which the method is called (staticmethods and classmethods are not considered now) A class can define a variety of special methods (two leading and two trailing underscores) relating to specific operation on its instances >>> class C5(object): ... """This is the docstring of the class. ... It can be accessed by C5. doc """ ... def hello(self): ... "And this the docstring of the method" ... print "Hello!!" J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 11 / 49
  • 64. Classes Function definitions in a class body Most class bodies include def statements since functions (called methods in this context) are important attributes for most class objects A method defined in a class body has a mandatory first parameter (conventionally called self) that refers to the instance on which the method is called (staticmethods and classmethods are not considered now) A class can define a variety of special methods (two leading and two trailing underscores) relating to specific operation on its instances >>> class C5(object): ... """This is the docstring of the class. ... It can be accessed by C5. doc """ ... def hello(self): ... "And this the docstring of the method" ... print "Hello!!" J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 11 / 49
  • 65. Classes Function definitions in a class body Most class bodies include def statements since functions (called methods in this context) are important attributes for most class objects A method defined in a class body has a mandatory first parameter (conventionally called self) that refers to the instance on which the method is called (staticmethods and classmethods are not considered now) A class can define a variety of special methods (two leading and two trailing underscores) relating to specific operation on its instances >>> class C5(object): ... """This is the docstring of the class. ... It can be accessed by C5. doc """ ... def hello(self): ... "And this the docstring of the method" ... print "Hello!!" J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 11 / 49
  • 66. Classes Function definitions in a class body Most class bodies include def statements since functions (called methods in this context) are important attributes for most class objects A method defined in a class body has a mandatory first parameter (conventionally called self) that refers to the instance on which the method is called (staticmethods and classmethods are not considered now) A class can define a variety of special methods (two leading and two trailing underscores) relating to specific operation on its instances >>> class C5(object): ... """This is the docstring of the class. ... It can be accessed by C5. doc """ ... def hello(self): ... "And this the docstring of the method" ... print "Hello!!" J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 11 / 49
  • 67. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 68. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 69. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 70. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 71. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 72. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 73. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 74. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 75. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 76. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 77. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 78. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 79. Instances I Creating Instances 1 To create an instance of a >>> anInstance = C5() class, call the class object as >>> isinstance(anInstance, C5) if it were a function True >>> class C6(object): If it defines or inherits ... def init (self, n): init , calling the class ... self.x = n object implicitly calls it to >>> anInstance = C6(42) perform any needed >>> print anInstance.x instance-specific 42 initialisation >>> anInstance.z = 8 You can give an instance an >>> print anInstance.z attribute by binding a value 8 to an attribute reference J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 12 / 49
  • 80. Instances I Attributes of Instance Objects Attributes can be bound inside or outside class methods >>> class C1(object): >>> class C2(object): ... def amethod(self, n=8): ... pass ... self.n = n >>> d = C2() >>> c = C1() >>> d.n = 15 >>> c.amethod() >>> print d.n >>> print c.n 15 8 Some attributes are implicitly set (both can be rebound but not unbound): >>> print d. class <class ’ main .C2’> >>> d. dict [’z’] = 42 >>> print d.z 42 >>> print d. dict [’n’] 15 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 13 / 49
  • 81. Instances I Attributes of Instance Objects Attributes can be bound inside or outside class methods >>> class C1(object): >>> class C2(object): ... def amethod(self, n=8): ... pass ... self.n = n >>> d = C2() >>> c = C1() >>> d.n = 15 >>> c.amethod() >>> print d.n >>> print c.n 15 8 Some attributes are implicitly set (both can be rebound but not unbound): >>> print d. class <class ’ main .C2’> >>> d. dict [’z’] = 42 >>> print d.z 42 >>> print d. dict [’n’] 15 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 13 / 49
  • 82. Instances I Attributes of Instance Objects Attributes can be bound inside or outside class methods >>> class C1(object): >>> class C2(object): ... def amethod(self, n=8): ... pass ... self.n = n >>> d = C2() >>> c = C1() >>> d.n = 15 >>> c.amethod() >>> print d.n >>> print c.n 15 8 Some attributes are implicitly set (both can be rebound but not unbound): >>> print d. class <class ’ main .C2’> >>> d. dict [’z’] = 42 >>> print d.z 42 >>> print d. dict [’n’] 15 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 13 / 49
  • 83. Instances I Attributes of Instance Objects Attributes can be bound inside or outside class methods >>> class C1(object): >>> class C2(object): ... def amethod(self, n=8): ... pass ... self.n = n >>> d = C2() >>> c = C1() >>> d.n = 15 >>> c.amethod() >>> print d.n >>> print c.n 15 8 Some attributes are implicitly set (both can be rebound but not unbound): >>> print d. class <class ’ main .C2’> >>> d. dict [’z’] = 42 >>> print d.z 42 >>> print d. dict [’n’] 15 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 13 / 49
  • 84. Instances I Attributes of Instance Objects Attributes can be bound inside or outside class methods >>> class C1(object): >>> class C2(object): ... def amethod(self, n=8): ... pass ... self.n = n >>> d = C2() >>> c = C1() >>> d.n = 15 >>> c.amethod() >>> print d.n >>> print c.n 15 8 Some attributes are implicitly set (both can be rebound but not unbound): >>> print d. class <class ’ main .C2’> >>> d. dict [’z’] = 42 >>> print d.z 42 >>> print d. dict [’n’] 15 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 13 / 49
  • 85. Instances I Attributes of Instance Objects Attributes can be bound inside or outside class methods >>> class C1(object): >>> class C2(object): ... def amethod(self, n=8): ... pass ... self.n = n >>> d = C2() >>> c = C1() >>> d.n = 15 >>> c.amethod() >>> print d.n >>> print c.n 15 8 Some attributes are implicitly set (both can be rebound but not unbound): >>> print d. class <class ’ main .C2’> >>> d. dict [’z’] = 42 >>> print d.z 42 >>> print d. dict [’n’] 15 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 13 / 49
  • 86. Instances I Attributes of Instance Objects Attributes can be bound inside or outside class methods >>> class C1(object): >>> class C2(object): ... def amethod(self, n=8): ... pass ... self.n = n >>> d = C2() >>> c = C1() >>> d.n = 15 >>> c.amethod() >>> print d.n >>> print c.n 15 8 Some attributes are implicitly set (both can be rebound but not unbound): >>> print d. class <class ’ main .C2’> >>> d. dict [’z’] = 42 >>> print d.z 42 >>> print d. dict [’n’] 15 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 13 / 49
  • 87. Descriptors Descriptors A descriptor is any new-style object whose class supplies a special method named get Descriptors that are class attributes control the semantics of accessing and setting attributes on instances of that class If a descriptor’s class also supplies method set then it is called an overriding descriptor (a.k.a. data descriptor) If not, it is called non-overriding (a.k.a. non-data) descriptor Function objects (and methods) are non-overriding descriptors Descriptors are the mechanism behind properties, methods, static methods, class methods, and super (cooperative super-classes) The descriptor protocol also contains method delete for unbinding attributes but it is seldom used J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 14 / 49
  • 88. Descriptors Descriptors A descriptor is any new-style object whose class supplies a special method named get Descriptors that are class attributes control the semantics of accessing and setting attributes on instances of that class If a descriptor’s class also supplies method set then it is called an overriding descriptor (a.k.a. data descriptor) If not, it is called non-overriding (a.k.a. non-data) descriptor Function objects (and methods) are non-overriding descriptors Descriptors are the mechanism behind properties, methods, static methods, class methods, and super (cooperative super-classes) The descriptor protocol also contains method delete for unbinding attributes but it is seldom used J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 14 / 49
  • 89. Descriptors Descriptors A descriptor is any new-style object whose class supplies a special method named get Descriptors that are class attributes control the semantics of accessing and setting attributes on instances of that class If a descriptor’s class also supplies method set then it is called an overriding descriptor (a.k.a. data descriptor) If not, it is called non-overriding (a.k.a. non-data) descriptor Function objects (and methods) are non-overriding descriptors Descriptors are the mechanism behind properties, methods, static methods, class methods, and super (cooperative super-classes) The descriptor protocol also contains method delete for unbinding attributes but it is seldom used J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 14 / 49
  • 90. Descriptors Descriptors A descriptor is any new-style object whose class supplies a special method named get Descriptors that are class attributes control the semantics of accessing and setting attributes on instances of that class If a descriptor’s class also supplies method set then it is called an overriding descriptor (a.k.a. data descriptor) If not, it is called non-overriding (a.k.a. non-data) descriptor Function objects (and methods) are non-overriding descriptors Descriptors are the mechanism behind properties, methods, static methods, class methods, and super (cooperative super-classes) The descriptor protocol also contains method delete for unbinding attributes but it is seldom used J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 14 / 49
  • 91. Descriptors Descriptors A descriptor is any new-style object whose class supplies a special method named get Descriptors that are class attributes control the semantics of accessing and setting attributes on instances of that class If a descriptor’s class also supplies method set then it is called an overriding descriptor (a.k.a. data descriptor) If not, it is called non-overriding (a.k.a. non-data) descriptor Function objects (and methods) are non-overriding descriptors Descriptors are the mechanism behind properties, methods, static methods, class methods, and super (cooperative super-classes) The descriptor protocol also contains method delete for unbinding attributes but it is seldom used J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 14 / 49
  • 92. Descriptors Descriptors A descriptor is any new-style object whose class supplies a special method named get Descriptors that are class attributes control the semantics of accessing and setting attributes on instances of that class If a descriptor’s class also supplies method set then it is called an overriding descriptor (a.k.a. data descriptor) If not, it is called non-overriding (a.k.a. non-data) descriptor Function objects (and methods) are non-overriding descriptors Descriptors are the mechanism behind properties, methods, static methods, class methods, and super (cooperative super-classes) The descriptor protocol also contains method delete for unbinding attributes but it is seldom used J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 14 / 49
  • 93. Descriptors Descriptors A descriptor is any new-style object whose class supplies a special method named get Descriptors that are class attributes control the semantics of accessing and setting attributes on instances of that class If a descriptor’s class also supplies method set then it is called an overriding descriptor (a.k.a. data descriptor) If not, it is called non-overriding (a.k.a. non-data) descriptor Function objects (and methods) are non-overriding descriptors Descriptors are the mechanism behind properties, methods, static methods, class methods, and super (cooperative super-classes) The descriptor protocol also contains method delete for unbinding attributes but it is seldom used J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 14 / 49
  • 94. Descriptors A Descriptor Example >>> class Area(object): ... """An overriding descriptor""" ... def get (self, obj, klass): ... return obj.x * obj.y ... def set (self, obj, value): ... raise AttributeError >>> class Rectangle(object): ... """A new-style class for representing rectangles""" ... area = Area() ... def init (self, x, y): ... self.x = x ... self.y = y >>> r = Rectangle(5, 10) >>> print r.area 50 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 15 / 49
  • 95. Descriptors Referencing Attributes Attribute Reference Basics An attribute reference is an expression of the form x.name, where x is an expression and name is an identifier Many kinds of Python objects have attributes, but an attribute reference when x refers to a class or an instance has special rich semantics The mechanics of attribute getting is defined in the special method getattribute The predefined behaviour is defined in the implementation of this method in the type (for class attributes) and object (for instance attributes) built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 16 / 49
  • 96. Descriptors Referencing Attributes Attribute Reference Basics An attribute reference is an expression of the form x.name, where x is an expression and name is an identifier Many kinds of Python objects have attributes, but an attribute reference when x refers to a class or an instance has special rich semantics The mechanics of attribute getting is defined in the special method getattribute The predefined behaviour is defined in the implementation of this method in the type (for class attributes) and object (for instance attributes) built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 16 / 49
  • 97. Descriptors Referencing Attributes Attribute Reference Basics An attribute reference is an expression of the form x.name, where x is an expression and name is an identifier Many kinds of Python objects have attributes, but an attribute reference when x refers to a class or an instance has special rich semantics The mechanics of attribute getting is defined in the special method getattribute The predefined behaviour is defined in the implementation of this method in the type (for class attributes) and object (for instance attributes) built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 16 / 49
  • 98. Descriptors Referencing Attributes Attribute Reference Basics An attribute reference is an expression of the form x.name, where x is an expression and name is an identifier Many kinds of Python objects have attributes, but an attribute reference when x refers to a class or an instance has special rich semantics The mechanics of attribute getting is defined in the special method getattribute The predefined behaviour is defined in the implementation of this method in the type (for class attributes) and object (for instance attributes) built-in types J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 16 / 49
  • 99. Descriptors Referencing Attributes Getting an attribute from a class When you use the syntax C.name to refer to an attribute on a class object C, the look-up proceeds in two steps: 1 When ’name’ is a key in C. dict , C.name fetches the value v from C. dict [’name’]. If v is a descriptor (i.e. type(v) supplies a get method), then type(v). get (v,None,C) is returned Otherwise, ir returns v 2 Otherwise, it delegates the look-up to its base classes (in method resolution order) When these look-ups steps do not find an attribute, Python raises an AttributeError exception. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 17 / 49
  • 100. Descriptors Referencing Attributes Getting an attribute from a class When you use the syntax C.name to refer to an attribute on a class object C, the look-up proceeds in two steps: 1 When ’name’ is a key in C. dict , C.name fetches the value v from C. dict [’name’]. If v is a descriptor (i.e. type(v) supplies a get method), then type(v). get (v,None,C) is returned Otherwise, ir returns v 2 Otherwise, it delegates the look-up to its base classes (in method resolution order) When these look-ups steps do not find an attribute, Python raises an AttributeError exception. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 17 / 49
  • 101. Descriptors Referencing Attributes Getting an attribute from a class When you use the syntax C.name to refer to an attribute on a class object C, the look-up proceeds in two steps: 1 When ’name’ is a key in C. dict , C.name fetches the value v from C. dict [’name’]. If v is a descriptor (i.e. type(v) supplies a get method), then type(v). get (v,None,C) is returned Otherwise, ir returns v 2 Otherwise, it delegates the look-up to its base classes (in method resolution order) When these look-ups steps do not find an attribute, Python raises an AttributeError exception. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 17 / 49
  • 102. Descriptors Referencing Attributes Getting an attribute from a class When you use the syntax C.name to refer to an attribute on a class object C, the look-up proceeds in two steps: 1 When ’name’ is a key in C. dict , C.name fetches the value v from C. dict [’name’]. If v is a descriptor (i.e. type(v) supplies a get method), then type(v). get (v,None,C) is returned Otherwise, ir returns v 2 Otherwise, it delegates the look-up to its base classes (in method resolution order) When these look-ups steps do not find an attribute, Python raises an AttributeError exception. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 17 / 49
  • 103. Descriptors Referencing Attributes Getting an attribute from a class When you use the syntax C.name to refer to an attribute on a class object C, the look-up proceeds in two steps: 1 When ’name’ is a key in C. dict , C.name fetches the value v from C. dict [’name’]. If v is a descriptor (i.e. type(v) supplies a get method), then type(v). get (v,None,C) is returned Otherwise, ir returns v 2 Otherwise, it delegates the look-up to its base classes (in method resolution order) When these look-ups steps do not find an attribute, Python raises an AttributeError exception. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 17 / 49
  • 104. Descriptors Referencing Attributes Getting an attribute from a class When you use the syntax C.name to refer to an attribute on a class object C, the look-up proceeds in two steps: 1 When ’name’ is a key in C. dict , C.name fetches the value v from C. dict [’name’]. If v is a descriptor (i.e. type(v) supplies a get method), then type(v). get (v,None,C) is returned Otherwise, ir returns v 2 Otherwise, it delegates the look-up to its base classes (in method resolution order) When these look-ups steps do not find an attribute, Python raises an AttributeError exception. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 17 / 49
  • 105. Descriptors Referencing Attributes Getting an attribute from a class When you use the syntax C.name to refer to an attribute on a class object C, the look-up proceeds in two steps: 1 When ’name’ is a key in C. dict , C.name fetches the value v from C. dict [’name’]. If v is a descriptor (i.e. type(v) supplies a get method), then type(v). get (v,None,C) is returned Otherwise, ir returns v 2 Otherwise, it delegates the look-up to its base classes (in method resolution order) When these look-ups steps do not find an attribute, Python raises an AttributeError exception. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 17 / 49
  • 106. Descriptors Referencing Attributes Getting an attribute from an instance I When you use the syntax x.name to refer to an attribute of instance x of class C, the look-up proceeds in three steps: 1 When ’name’ is found in C (or in one of C’s ancestor classes) as the name of an overriding descriptor v (i.e. type(v) supplies both get and set ), then the value of x.name is type(v). get (v,x,C) 2 Otherwise, when ’name’ is key in x. dict , x.name fetches and returns x. dict [’name’] 3 Otherwise, x.name delegates the look-up to x’s class (looking into C. dict or delegating to C’s bases) and if a descriptor v is found, the overall result is again type(v). get (v,x,C). if a nondescriptor value v is found, the result is v. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 18 / 49
  • 107. Descriptors Referencing Attributes Getting an attribute from an instance I When you use the syntax x.name to refer to an attribute of instance x of class C, the look-up proceeds in three steps: 1 When ’name’ is found in C (or in one of C’s ancestor classes) as the name of an overriding descriptor v (i.e. type(v) supplies both get and set ), then the value of x.name is type(v). get (v,x,C) 2 Otherwise, when ’name’ is key in x. dict , x.name fetches and returns x. dict [’name’] 3 Otherwise, x.name delegates the look-up to x’s class (looking into C. dict or delegating to C’s bases) and if a descriptor v is found, the overall result is again type(v). get (v,x,C). if a nondescriptor value v is found, the result is v. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 18 / 49
  • 108. Descriptors Referencing Attributes Getting an attribute from an instance I When you use the syntax x.name to refer to an attribute of instance x of class C, the look-up proceeds in three steps: 1 When ’name’ is found in C (or in one of C’s ancestor classes) as the name of an overriding descriptor v (i.e. type(v) supplies both get and set ), then the value of x.name is type(v). get (v,x,C) 2 Otherwise, when ’name’ is key in x. dict , x.name fetches and returns x. dict [’name’] 3 Otherwise, x.name delegates the look-up to x’s class (looking into C. dict or delegating to C’s bases) and if a descriptor v is found, the overall result is again type(v). get (v,x,C). if a nondescriptor value v is found, the result is v. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 18 / 49
  • 109. Descriptors Referencing Attributes Getting an attribute from an instance I When you use the syntax x.name to refer to an attribute of instance x of class C, the look-up proceeds in three steps: 1 When ’name’ is found in C (or in one of C’s ancestor classes) as the name of an overriding descriptor v (i.e. type(v) supplies both get and set ), then the value of x.name is type(v). get (v,x,C) 2 Otherwise, when ’name’ is key in x. dict , x.name fetches and returns x. dict [’name’] 3 Otherwise, x.name delegates the look-up to x’s class (looking into C. dict or delegating to C’s bases) and if a descriptor v is found, the overall result is again type(v). get (v,x,C). if a nondescriptor value v is found, the result is v. J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2009-2010 18 / 49