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 (20)

Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
NUMPY
NUMPY NUMPY
NUMPY
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
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
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Presentation on data preparation with pandas
Presentation on data preparation with pandasPresentation on data preparation with pandas
Presentation on data preparation with pandas
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPy
 
Python ppt
Python pptPython ppt
Python ppt
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming ppt
 
pandas - Python Data Analysis
pandas - Python Data Analysispandas - Python Data Analysis
pandas - Python Data Analysis
 
Python for Data Science
Python for Data SciencePython for Data Science
Python for Data Science
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 

Viewers also liked

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 MinutesMatt Harrison
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 
Memory Management In Python The Basics
Memory Management In Python The BasicsMemory Management In Python The Basics
Memory Management In Python The BasicsNina Zakharenko
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
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)Paige Bailey
 
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 WithoutAudrey Roy
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Thinking hard about_python
Thinking hard about_pythonThinking hard about_python
Thinking hard about_pythonDaniel Greenfeld
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)Matt Harrison
 
Verilerimi düzenliyorum
Verilerimi düzenliyorumVerilerimi düzenliyorum
Verilerimi düzenliyorumİsmail Keskin
 
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...Matt Harrison
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners Sujith Kumar
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming LanguageDr.YNM
 

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
 
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)
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming Language
 

Similar to Object-oriented Programming in Python

Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in PythonJordi Vilaplana
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in pythonnitamhaske
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4Binay Kumar Ray
 
PHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptxPHP OOP Lecture - 01.pptx
PHP OOP Lecture - 01.pptxAtikur Rahman
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 
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 completeHarish Gyanani
 
Using at least two examples (whenever applicable), concisely discuss .pdf
Using at least two examples (whenever applicable), concisely discuss .pdfUsing at least two examples (whenever applicable), concisely discuss .pdf
Using at least two examples (whenever applicable), concisely discuss .pdfrajeshjangid1865
 
lec(1).pptx
lec(1).pptxlec(1).pptx
lec(1).pptxMemMem25
 
Python-Mastering-the-Language-of-Data-Science.pptx
Python-Mastering-the-Language-of-Data-Science.pptxPython-Mastering-the-Language-of-Data-Science.pptx
Python-Mastering-the-Language-of-Data-Science.pptxdmdHaneef
 
Object Oriented Programming Overview for the PeopleSoft Developer
Object Oriented Programming Overview for the PeopleSoft DeveloperObject Oriented Programming Overview for the PeopleSoft Developer
Object Oriented Programming Overview for the PeopleSoft DeveloperLee Greffin
 
1 intro
1 intro1 intro
1 introabha48
 

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

More from Juan-Manuel Gimeno

Visualización de datos enlazados
Visualización de datos enlazadosVisualización de datos enlazados
Visualización de datos enlazadosJuan-Manuel Gimeno
 
Functional programming in clojure
Functional programming in clojureFunctional programming in clojure
Functional programming in clojureJuan-Manuel Gimeno
 
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)Juan-Manuel Gimeno
 
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.0Juan-Manuel Gimeno
 
Metaclass Programming in Python
Metaclass Programming in PythonMetaclass Programming in Python
Metaclass Programming in PythonJuan-Manuel Gimeno
 
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 StyleJuan-Manuel Gimeno
 

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

USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 

Recently uploaded (20)

USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 

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