Objects and classes. Objects and classes. Jarkko Toivonen (CS Department) Programming in Python 1



Similar documents
Python Classes and Objects

Software Tool Seminar WS Taming the Snake

Object Oriented Software Design II

Introduction to Python

Programming in Python. Basic information. Teaching. Administration Organisation Contents of the Course. Jarkko Toivonen. Overview of Python

2! Multimedia Programming with! Python and SDL

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

Outline Basic concepts of Python language

CSC 221: Computer Programming I. Fall 2011

Sorting. Lists have a sort method Strings are sorted alphabetically, except... Uppercase is sorted before lowercase (yes, strange)

Moving from CS 61A Scheme to CS 61B Java

Code Qualities and Coding Practices

Chapter 15 Functional Programming Languages

UNIVERSITY OF CALIFORNIA BERKELEY Engineering 7 Department of Civil and Environmental Engineering. Object Oriented Programming and Classes in MATLAB 1

Name Spaces. Introduction into Python Python 5: Classes, Exceptions, Generators and more. Classes: Example. Classes: Briefest Introduction

Java Classes. GEEN163 Introduction to Computer Programming

Exercise 1: Python Language Basics

ILS Indenting Management Business Process User Guide. ILS Indenting Management Business Process User Guide

Part I. Multiple Choice Questions (2 points each):

2/1/2010. Background Why Python? Getting Our Feet Wet Comparing Python to Java Resources (Including a free textbook!) Hathaway Brown School

61A Lecture 16. Friday, October 11

THE IMPACT OF INHERITANCE ON SECURITY IN OBJECT-ORIENTED DATABASE SYSTEMS

Intro to scientific programming (with Python) Pietro Berkes, Brandeis University

The Command Dispatcher Pattern

Basic Object-Oriented Programming in Java

Introduction to Programming Languages and Techniques. xkcd.com FULL PYTHON TUTORIAL

Instruction Set Architecture of Mamba, a New Virtual Machine for Python

It is the thinnest layer in the OSI model. At the time the model was formulated, it was not clear that a session layer was needed.

Introduction to Python

PyLmod Documentation. Release MIT Office of Digital Learning

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Object Oriented Databases. OOAD Fall 2012 Arjun Gopalakrishna Bhavya Udayashankar

Meß- und Kommunikationstechnik GmbH Annaberger Str Chemnitz Tel

Exploring Algorithms with Python

LAB4 Making Classes and Objects

Crash Dive into Python

Python CS1 as Preparation for C++ CS2

Python Loops and String Manipulation

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

CS 111 Classes I 1. Software Organization View to this point:

JupyterHub Documentation

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

pyownet Documentation

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Python Objects. Charles Severance

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Python Evaluation Rules

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Exercise 0. Although Python(x,y) comes already with a great variety of scientic Python packages, we might have to install additional dependencies:

Python Documentation & Startup

Python for Rookies. Example Examination Paper

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Object-Oriented Databases

Student Outcomes. Lesson Notes. Classwork. Discussion (10 minutes)

Profiling, debugging and testing with Python. Jonathan Bollback, Georg Rieckh and Jose Guzman

Introduction to Python

1. What are Data Structures? Introduction to Data Structures. 2. What will we Study? CITS2200 Data Structures and Algorithms

SQL Tables, Keys, Views, Indexes

6.170 Tutorial 3 - Ruby Basics

The C Programming Language course syllabus associate level

0.5 Lab: Introduction to Python sets, lists, dictionaries, and comprehensions

Software Development (CS2500)

Python 2 and 3 compatibility testing via optional run-time type checking

Hands-On Python A Tutorial Introduction for Beginners Python 3.1 Version

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Python Lists and Loops

Corba. Corba services. The (very) global picture. Corba. Distributed Object Systems 3 CORBA/IDL. Corba. Features. Services

Computer Programming I

Hash-flooding DoS reloaded: attacks and defenses

Answers included WORKSHEET: INTEGRITY CONTROL IN RELATIONAL DATABASES

Concepts and terminology in the Simula Programming Language

Appendix... B. The Object Constraint

CRASH COURSE PYTHON. Het begint met een idee

Exercise 4 Learning Python language fundamentals

Object Oriented Programming and the Objective-C Programming Language 1.0. (Retired Document)

Assignment 2: Option Pricing and the Black-Scholes formula The University of British Columbia Science One CS Instructor: Michael Gelbart

CS 378 Big Data Programming. Lecture 9 Complex Writable Types

McGraw-Hill The McGraw-Hill Companies, Inc.,

Self-review 9.3 What is PyUnit? PyUnit is the unit testing framework that comes as standard issue with the Python system.

Chapter 1: Key Concepts of Programming and Software Engineering

Object Oriented Databases (OODBs) Relational and OO data models. Advantages and Disadvantages of OO as compared with relational

The HTTP Plug-in. Table of contents

Programming Using Python

Python for Test Automation i. Python for Test Automation

Introduction to Java Lecture Notes. Ryan Dougherty

Evolution of the Major Programming Languages

Programming and Software Development CTAG Alignments

Programming Languages CIS 443

11 November

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I)

Introduction to Object-Oriented Programming

PYTHON Basics

Tuple spaces and Object spaces. Distributed Object Systems 12. Tuple spaces and Object spaces. Communication. Tuple space. Mechanisms 2.

Physical Design. Meeting the needs of the users is the gold standard against which we measure our success in creating a database.

Transcription:

Objects and classes Jarkko Toivonen (CS Department) Programming in Python 1

Programming paradigms of Python Python is an object-oriented programming language like Java and C++ But unlike Java, Python doesn t force you to use classes, inheritance and methods If you like, you can also choose the structural programming paradigm with functions and modules Jarkko Toivonen (CS Department) Programming in Python 2

Objects in Python Every value in Python is an object Objects are a way to combine data and the functions that handle that data This combination is called encapsulation The data items and functions of objects are called attributes, and in particular the function attributes are called methods For example, the operator + on integers calls a method of integers, and the operator + on strings calls a method of strings Jarkko Toivonen (CS Department) Programming in Python 3

First class objects Functions, modules, methods, classes, etc are all first class objects This means that these objects can be stored in a container passed to a function as a parameter returned by a function used as a key to a dictionary bound to a variable Jarkko Toivonen (CS Department) Programming in Python 4

Referring to attributes One can access an attribute of an object using the dot operator: object.attribute For example: if L is a list, we can refer to the method append with L.append. The method call can look, for instance, like this: L.append(4) Because also modules are objects in Python, we can interpret the expression math.pi as accessing the data attribute pi of module object math Jarkko Toivonen (CS Department) Programming in Python 5

Types and instances Numbers like 2 and 100 are instances of type int. Similarly, "hello" is an instance of type str. When we write s=set(), we are actually creating a new instance of type set, and bind the resulting instance object to s Jarkko Toivonen (CS Department) Programming in Python 6

Classes and instance objects A user can define his own data types These are called classes A user can call these classes like they were functions, and they return a new instance object of that type Classes can be thought as recipes for creating objects Jarkko Toivonen (CS Department) Programming in Python 7

Class definition 1 An example of class definition class MyClass(object): """Documentation string of the class""" def init (self, param1, param2): "This initialises an instance of type ClassName" self.b = param1 # creates an instance attribute c = param2 # creates a local variable # statements... def f(self, param1): """This is a method of the class""" # some statements a=1 # This creates a class attribute Jarkko Toivonen (CS Department) Programming in Python 8

Class definition 2 The class definition starts with the class statement With this statement you give a name for your new type, and also in parentheses list the base classes of your class The next indented block is the class body After the whole class body is read, a new type is created Note that no instances are created yet All the attributes and methods of the class are defined in the class body Jarkko Toivonen (CS Department) Programming in Python 9

Class definition 3 The example class has two methods: init and f Note that their first parameter is special: self. It corresponds to this variable of C++ or Java init does the initialisation when an instance is created At instantiation with i=myclass(2,3) the parameters param1 and param2 are bound to values 2 and 3, respectively Now that we have an instance i, we can call its method f with the dot operator: i.f(1) The parameters of f are bound in the following way: self=i and param1=1 Jarkko Toivonen (CS Department) Programming in Python 10

Class definition 4 There are differences in how an assignment inside a class creates variables The attribute a is at class level and is common for all instances of the class MyClass The variable c is a local variable of the function cannot therefore be used outside the function init, and The attribute b is specific to each instance of MyClass. Note that self refers to the current instance An example: for objects x=myclass(1,0) and y=myclass(2,0) we have x.b!= y.b, but x.a == y.a Jarkko Toivonen (CS Department) Programming in Python 11

Methods All methods of a class have a mandatory first parameter which refers to the instance on which you called the method This parameter is usually named self If you want to access the class attribute a from a method of the class, use the fully qualified form MyClass.a The methods whose names both begin and end with two underscores are called special methods. For example, init is a special method. These methods will be discussed in detail later Jarkko Toivonen (CS Department) Programming in Python 12

Class attributes If a name in Python begins with an underscore, it means that the name is meant to be private. For instance, the name hidden is a private name This means you should not try to access that name. It is just some implementation specific name, not part of the public interface This is meant to be a hint for a user. Python itself doesn t enforce this rule The attributes doc and bases exists for every class, and contain the docstring of the class and the tuple of base classes, respectively Jarkko Toivonen (CS Department) Programming in Python 13

Instances 1 We can create instances by calling a class like it were a function: i = ClassName(...) Then parameters given in the call will be passed to the init function In the init method you can create the instance specific attributes If init is missing, we can create an instance without giving any parameters. As a consequence, the instance has no attributes Later you can (re)bind attributes with the assignment instance.attribute = new value Jarkko Toivonen (CS Department) Programming in Python 14

Instances 2 If that attribute did not exist before, it will be added to the instance with the assigned value In Python we really can add or delete attributes to/from an existing instance This is possible because the attribute names and the corresponding values are actually stored in a dictionary This dictionary is also an attribute of the instance and is called dict Another standard attribute in addition to dict is called class. This attribute stores the class of the instance. That is, the type of the object Jarkko Toivonen (CS Department) Programming in Python 15

Attribute lookup (simplified version) 1 Suppose x is an instance of class X, and we want to read an attribute x.a The lookup has three phases: First it is checked whether the attribute a is an attribute of the instance x If not, then it is checked whether a is a class attribute of x s class X If not, then the base classes of X are checked Jarkko Toivonen (CS Department) Programming in Python 16

Attribute lookup (simplified version) 2 If instead we want to bind the attribute a, things are much simpler x.a = value will set the instance attribute And X.a = value will set the class attribute Note that if a base of X, the class X, and the instance x each have an attribute called a, then x.a hides X.a, and X.a hides the attribute of the base class Jarkko Toivonen (CS Department) Programming in Python 17