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

Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class designNeetu Mishra
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - RecursionAdan Hubahib
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingMoutaz Haddara
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classesShreyans Pathak
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)Jyoti shukla
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming Raghunath A
 

What's hot (20)

Inheritance in OOPS
Inheritance in OOPSInheritance in OOPS
Inheritance in OOPS
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
 
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)
 
Object Oriented Design
Object Oriented DesignObject Oriented Design
Object Oriented Design
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
concept of oops
concept of oopsconcept of oops
concept of oops
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
 
Python made easy
Python made easy Python made easy
Python made easy
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
OOP java
OOP javaOOP java
OOP java
 

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
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
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
 

Viewers also liked (20)

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

Similar to Object-oriented Programming in Python

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

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Recently uploaded (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

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