CNRS ANF PYTHON Objects everywhere

Similar documents
Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Beyond Blocks: Python Session #1

Data Structures (list, dictionary, tuples, sets, strings)

CSCE 110 Programming I

Introduction to Programming Using Java (98-388)

Python INTRODUCTION: Understanding the Open source Installation of python in Linux/windows. Understanding Interpreters * ipython.

Python Reference (The Right Way) Documentation

Python in 10 (50) minutes

Introduction to Python programming, II

What's New in Python 2.2

Advanced Algorithms and Computational Models (module A)

Software Development Python (Part B)

Object Model Comparisons

Java Object Oriented Design. CSC207 Fall 2014

Friday, 11 April 14. Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014

PYTHON CONTENT NOTE: Almost every task is explained with an example

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

Python Interview Questions & Answers

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Chapter 11 Object and Object- Relational Databases

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

CIS192 Python Programming. Robert Rand. August 27, 2015

CSI33 Data Structures

Python 3000 and You. Guido van Rossum PyCon March 14, 2008

CNRS ANF PYTHON Packaging & Life Cycle

Objects and classes in Python Documentation

Table of Contents. Preface... xxi

CIS192 Python Programming

The Pyth Language. Administrivia

Fun with Python Descriptors

CIS192: Python Programming

CIS192 Python Programming

Python Basics. Lecture and Lab 5 Day Course. Python Basics

Introduction to Python programming, II

DSC 201: Data Analysis & Visualization

Announcements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration

COP 3330 Final Exam Review

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

DSC 201: Data Analysis & Visualization

CS 11 python track: lecture 4

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2

COMP 364: Functions II

Object Oriented Programming

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

CIS192 Python Programming

Introduction to Python

PYTHON TRAINING COURSE CONTENT

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

Python Review IPRE

Collections. Lists, Tuples, Sets, Dictionaries

Outline. Outline. 1 Chapter 2: Data Abstraction

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

Computational Concepts Toolbox. Object Oriented Programming. Today: class. Review: Objects

CS Lecture 26: Grab Bag. Announcements

funcsigs Documentation

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013

Data Structures. Lists, Tuples, Sets, Dictionaries

Inheritance and Polymorphism

COMP1730/COMP6730 Programming for Scientists. Testing and Debugging.

Lessons on Python Classes and Objects

Sharing, mutability, and immutability. Ruth Anderson UW CSE 160 Spring 2018

Lecture 02, Fall 2018 Friday September 7

Java Fundamentals (II)

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Overloading, Type Classes, and Algebraic Datatypes

Table of Contents EVALUATION COPY

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

Ruby: Introduction, Basics

Connexion Documentation

Object oriented programming. Encapsulation. Polymorphism. Inheritance OOP

PTN-105 Python programming. Course Outline. Prerequisite: basic Linux/UNIX and programming skills. Delivery Method: Instructor-led training (ILT)

Sage Reference Manual: Python technicalities

redis-lua Documentation

Python Decorators. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 28, 2010

Modules and scoping rules

Python - Variable Types. John R. Woodward

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Swift. Introducing swift. Thomas Woodfin

pygtrie Release Jul 03, 2017

Python Programming, bridging course 2011

Python Tips and Tricks


PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

New York University School of Continuing and Professional Studies Management and Information Technology. Advanced Python. Homework, Session 5

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

PREPARING FOR THE FINAL EXAM

Course Outline - COMP150. Lectures and Labs

61A Lecture 16. Wednesday, October 5

Chapter 4 Defining Classes I

15CS45 : OBJECT ORIENTED CONCEPTS

Semester 2. Structured Programming. Modular Programming Top-down design. Essentials covered. More complex programming topics.

CS Lecture 18: Card Tricks. Announcements. Slides by D. Gries, L. Lee, S. Marschner, W. White

Transcription:

CNRS ANF PYTHON Objects everywhere Marc Poinot Numerical Simulation Dept.

Outline Python Object oriented features Basic OO concepts syntax More on Python classes multiple inheritance reuse introspection mechanisms decorators operators others NSCOPE-PRS-024/2/20

Interface An object is an interface Visible part of the object Functions Constants Behavior Example: Phone Encapsulation Isolation 1 2 Interface Implémentation NSCOPE-PRS-024/3/20

Python OO remarks No interface Difficult to set a interface in a interpreted language Run-time evaluation may change behaviour Even if's very dangerous No abstract classes No function signature Cannot identify a method with its name & args Life cycle function specifics Due to python object life cycle Copy constructor, Destructeur, Init vs New NSCOPE-PRS-024/4/20

Basics - 1 A class is a type syntax An object is a value A variable is a reference to a value A class is a value class keyword class scope variables are attribute class scope functions are methods mandatory first argument of method is the current object by convention self variable name used for this first argument NSCOPE-PRS-024/5/20

Basics - 2 Base class The common part of all its subclasses A subclass can be a base class A derivation is the creation of a new class from a base class Methods overloading Methods of same name are masking base's methods Methods identification only uses the name, not the args Special methods Methods with special names Some methods are automatically called, for example: create delete Operators Never change the semantics of the overloaded operators NSCOPE-PRS-024/6/20

Factorization & Derivation - 1 Factorization Same interface Restrictions Extensions A factorization is an arbitrary process Object None Numbers Integers Plain integers Long integers Booleans Floating point Complex numbers Sequences Immutable sequences Strings Unicode Tuples Mutable sequences Lists Set types Sets Frozen sets Mappings Dictionaries Target is the application Sets are not Sequences Integers are not Reals Immutable sequences are not readonly Mutable sequences Same values may lead to different class hierarchy NSCOPE-PRS-024/7/20

Factorization & Derivation - 2 Two classes same interface class ListeEntiers: def init (self): self.values=[] def add(self,v): self.values.append(v) def max(self): m=self.values[0] for v in self.values: if (v>m): m=v return m def count(self): return len(self.values) class EnsembleEntiers: def init (self): self.values=[] def add(self,v): if (v not in self.values): self.values.append(v) def max(self): m=self.values[0] for v in self.values: if (v>m): m=v return m def count(self): return len(self.values) l=listeentiers() l.add(2) l.add(3) l.add(2) print l.max(), l.count() e=ensembleentiers() e.add(2) e.add(3) e.add(2) print e.max(), e.count() NSCOPE-PRS-024/8/20

Factorization & Derivation - 3 Factorization class ListeEntiers: def init (self): self.values=[] def add(self,v): self.values.append(v) class EnsembleEntiers(ListeEntiers): def add(self,v): if (v not in self.values): self.values.append(v) def max(self): m=self.values[0] for v in self.values: if (v>m): m=v return m def count(self): return len(self.values) NSCOPE-PRS-024/9/20

Factorization & Derivation - 4 Specialization class ListeEntiers: def init (self): self.values=[] def add(self,v): self.values.append(v) def max(self): m=self.values[0] for v in self.values: if (v>m): m=v return m class EnsembleEntiers(ListeEntiers): def add(self,v): if (v not in self.values): self.values.append(v) def remove(self,v): self.values.remove(v) def count(self): return len(self.values) def has(self,v): return v in self.values NSCOPE-PRS-024/10/20

Factorization & Derivation - 5 Simple derivation class Parallelepiped(numpy.ndarray) class Serializable(object) Use super() to find out base class ndarray Paralellepiped Serializable Multiple derivation class Square(Parallelepiped,Serializable) Square Method Resolution Order Square, Parallelepiped, Serializable, ndarray,..., object Methods are called wrt the MRO (depth first) NSCOPE-PRS-024/11/20

Class indentification & introspection isinstance(o,c) check object O is of class C or one of its base class issubclass(c,b) check class C has B as base class Method resolution order C.mro() module inspect large set of function to parse and retrieve info inspect.getmembers(parser, predicate=inspect.ismethod) Variable browsing difficult to find back variables dir(), globals(), locals() NSCOPE-PRS-024/12/20

Methods method callable class attribute object as first arg to be run on object values mesh.actualmemory() classmethod to be run on class values, no object required class as first arg Mesh.requiredMemory() @classmethod staticmethod no class no self as arg Mesh.getMaxMemory() @staticmethod A property is a synctactic trick: @property def f(): pass NSCOPE-PRS-024/13/20

Special methods - 1 init vs new new(cls, *args) creation takes the class as arg returns the new instance ndarray: no init in order to be able to change actual class init(self, *args) initialisation takes the new instance as arg returns self del Refcount reaches zero NSCOPE-PRS-024/14/20

Special methods - 2 Isolate interface/ implementation attribute maybe actual value, function, proxy getter/setter usual pattern class A(object): def init (self,*args): self.data=none a=a() a.data=4 v=a.data class A(object): def init (self,*args): self._data=none def set_data(self,value) self._data=value def get_data(self): return self._data a=a() a.set_data(4) class A(object): def init (self,*args): self._data=none @property def data(self): return self._data @data.setter def data(self,value) self.data=value a=a() a.data=4 NSCOPE-PRS-024/15/20

Special methods - 3 Context Manager enter exit Call from with as clause Prepare a context and release/ clean context More attribute isolation getattr setattr Trap attribute access Attribute should not already exist On the fly check/ generation NSCOPE-PRS-024/16/20

Reuse Derive from python objects Base class of all classes object Recommanded in 2.x Extensions types ndarray Exception classes Exception bool int float str unicode tuple list dict set frozenset map NSCOPE-PRS-024/17/20

Practical Training - 1 Forewords You can find simpler ways to define classes and methods and other mechanisms. The training tries to show many features in a short amount of time and in short pieces of software. The training classes are complex on purpose. Add classes in a new meshes.py Change square, rectangle, cube, parallelepiped function into classes of same name Use Mesh(ndarray) and Serialization(object) as base class Add something like g0.dbg('rectangle new') to print debug trace Add something like Mesh.set_dbg(True) to set trace on Create Exception for max size exceeded Add introspection functions issubclass, isinstance, mro, inspect.methods... NSCOPE-PRS-024/18/20

Practical Training - 2 Serialization Store the current state of the object Use Pickle Use a specific constructor Hold all context/ state of object Write a generator to perform: for m in Mesh.notArchivedinstances(): m.doarchive() NSCOPE-PRS-024/19/20

Practical Training - 3 Build a factory NSCOPE-PRS-024/20/20