SlideShare a Scribd company logo
1 of 233
Download to read offline
Object Oriented Programming in Python

                                     Juan Manuel Gimeno Illa
                                       jmgimeno@diei.udl.cat

                                         Curs 2007-2008




J.M.Gimeno (jmgimeno@diei.udl.cat)          OOP in Python      Curs 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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):
 ...     quot;quot;quot;This is the docstring of the class.
 ...     It can be accessed by C5. doc quot;quot;quot;
 ...     def hello(self):
 ...         quot;And this the docstring of the methodquot;
 ...         print quot;Hello!!quot;




J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python               Curs 2007-2008   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):
 ...     quot;quot;quot;This is the docstring of the class.
 ...     It can be accessed by C5. doc quot;quot;quot;
 ...     def hello(self):
 ...         quot;And this the docstring of the methodquot;
 ...         print quot;Hello!!quot;




J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python               Curs 2007-2008   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):
 ...     quot;quot;quot;This is the docstring of the class.
 ...     It can be accessed by C5. doc quot;quot;quot;
 ...     def hello(self):
 ...         quot;And this the docstring of the methodquot;
 ...         print quot;Hello!!quot;




J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python               Curs 2007-2008   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):
 ...     quot;quot;quot;This is the docstring of the class.
 ...     It can be accessed by C5. doc quot;quot;quot;
 ...     def hello(self):
 ...         quot;And this the docstring of the methodquot;
 ...         print quot;Hello!!quot;




J.M.Gimeno (jmgimeno@diei.udl.cat)    OOP in Python               Curs 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   14 / 49
Descriptors


A Descriptor Example
 >>>    class Area(object):
 ...       quot;quot;quot;An overriding descriptorquot;quot;quot;
 ...        def get (self, obj, klass):
 ...            return obj.x * obj.y
 ...        def set (self, obj, value):
 ...            raise AttributeError
 >>>    class Rectangle(object):
 ...        quot;quot;quot;A new-style class for representing rectanglesquot;quot;quot;
 ...        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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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 2007-2008   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

More Related Content

What's hot

What's hot (20)

Python Modules
Python ModulesPython Modules
Python Modules
 
Lecture 01 - Basic Concept About OOP With Python
Lecture 01 - Basic Concept About OOP With PythonLecture 01 - Basic Concept About OOP With Python
Lecture 01 - Basic Concept About OOP With Python
 
Python functions
Python functionsPython functions
Python functions
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners Object Oriented Programming Concepts for beginners
Object Oriented Programming Concepts for beginners
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
C++ OOPS Concept
C++ OOPS ConceptC++ OOPS Concept
C++ OOPS Concept
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and Modules
 
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
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Python Generators
Python GeneratorsPython Generators
Python Generators
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)
 

Viewers also liked

Verilerimi düzenliyorum
Verilerimi düzenliyorumVerilerimi düzenliyorum
Verilerimi düzenliyorum
İsmail Keskin
 

Viewers also liked (20)

Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The Basics
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python Worst Practices
Python Worst PracticesPython Worst Practices
Python Worst Practices
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Python/Django Training
Python/Django TrainingPython/Django Training
Python/Django Training
 
An Introduction to Python Concurrency
An Introduction to Python ConcurrencyAn Introduction to Python Concurrency
An Introduction to Python Concurrency
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live Without
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Thinking hard about_python
Thinking hard about_pythonThinking hard about_python
Thinking hard about_python
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
Verilerimi düzenliyorum
Verilerimi düzenliyorumVerilerimi düzenliyorum
Verilerimi düzenliyorum
 
Dili kullanmak
Dili kullanmakDili kullanmak
Dili kullanmak
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
 
Python 101
Python 101Python 101
Python 101
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)
 

Similar to Object-oriented Programming in Python

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
rajeshjangid1865
 
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
dmdHaneef
 

Similar to 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
 
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
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4
 
Python-Classes.pptx
Python-Classes.pptxPython-Classes.pptx
Python-Classes.pptx
 
PHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptxPHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptx
 
PYTHON PPT.pptx
PYTHON PPT.pptxPYTHON PPT.pptx
PYTHON PPT.pptx
 
12th ip CBSE chapter 4 oop in java notes complete
12th ip CBSE  chapter 4 oop in java notes complete12th ip CBSE  chapter 4 oop in java notes complete
12th ip CBSE chapter 4 oop in java notes complete
 
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
 
lec(1).pptx
lec(1).pptxlec(1).pptx
lec(1).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
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
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
 
1 intro
1 intro1 intro
1 intro
 
Chapter 1.pptx
Chapter 1.pptxChapter 1.pptx
Chapter 1.pptx
 
Unit 1 OOSE
Unit 1 OOSE Unit 1 OOSE
Unit 1 OOSE
 
Chapter1 introduction
Chapter1 introductionChapter1 introduction
Chapter1 introduction
 
OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Unit 5.ppt
Unit 5.pptUnit 5.ppt
Unit 5.ppt
 

More from Juan-Manuel Gimeno (8)

Visualización de datos enlazados
Visualización de datos enlazadosVisualización de datos enlazados
Visualización de datos enlazados
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojure
 
Sistemas de recomendación
Sistemas de recomendaciónSistemas de recomendación
Sistemas de recomendación
 
Proves de Software (en Java amb JUnit)
Proves de Software (en Java amb JUnit)Proves de Software (en Java amb JUnit)
Proves de Software (en Java amb JUnit)
 
Conceptes bàsics de la Web 2.0
Conceptes bàsics de la Web 2.0Conceptes bàsics de la Web 2.0
Conceptes bàsics de la Web 2.0
 
Unicode (and Python)
Unicode (and Python)Unicode (and Python)
Unicode (and Python)
 
Metaclass Programming in Python
Metaclass Programming in PythonMetaclass Programming in Python
Metaclass Programming in Python
 
Python: the Project, the Language and the Style
Python: the Project, the Language and the StylePython: the Project, the Language and the Style
Python: the Project, the Language and the Style
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Recently uploaded (20)

How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 

Object-oriented Programming in Python

  • 1. Object Oriented Programming in Python Juan Manuel Gimeno Illa jmgimeno@diei.udl.cat Curs 2007-2008 J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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): ... quot;quot;quot;This is the docstring of the class. ... It can be accessed by C5. doc quot;quot;quot; ... def hello(self): ... quot;And this the docstring of the methodquot; ... print quot;Hello!!quot; J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2007-2008 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): ... quot;quot;quot;This is the docstring of the class. ... It can be accessed by C5. doc quot;quot;quot; ... def hello(self): ... quot;And this the docstring of the methodquot; ... print quot;Hello!!quot; J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2007-2008 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): ... quot;quot;quot;This is the docstring of the class. ... It can be accessed by C5. doc quot;quot;quot; ... def hello(self): ... quot;And this the docstring of the methodquot; ... print quot;Hello!!quot; J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2007-2008 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): ... quot;quot;quot;This is the docstring of the class. ... It can be accessed by C5. doc quot;quot;quot; ... def hello(self): ... quot;And this the docstring of the methodquot; ... print quot;Hello!!quot; J.M.Gimeno (jmgimeno@diei.udl.cat) OOP in Python Curs 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 14 / 49
  • 94. Descriptors A Descriptor Example >>> class Area(object): ... quot;quot;quot;An overriding descriptorquot;quot;quot; ... def get (self, obj, klass): ... return obj.x * obj.y ... def set (self, obj, value): ... raise AttributeError >>> class Rectangle(object): ... quot;quot;quot;A new-style class for representing rectanglesquot;quot;quot; ... 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 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 2007-2008 18 / 49