A Crash Course in Python Part II. Presented by Cuauhtémoc Carbajal ITESM CEM

Similar documents
CMSC201 Computer Science I for Majors

Object Oriented Programming in Python

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

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

EPL451: Data Mining on the Web Lab 4

Python Interpreted language: work with an evaluator for language expressions (like DrJava, but more flexible) Dynamically typed

CSE : Python Programming

Classes and Objects 1

MITOCW watch?v=flgjisf3l78

CS 11 python track: lecture 4

Full Python Tutorial. Python. Language features. Dynamic typing the key difference. Why Python? Introduction to Programming Languages and Techniques

Intro. Classes & Inheritance

CMSC201 Computer Science I for Majors

MITOCW MIT6_01SC_rec2_300k.mp4

Objects and Classes. Chapter 8

Object-Oriented Python

Object Model Comparisons

Programming I. Course 9 Introduction to programming

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes

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

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation.

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

Introduction to Python programming, II

Object Oriented Programming

COMP1730/COMP6730 Programming for Scientists. Testing and Debugging.

Inheritance (IS A Relationship)

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

CMSC 132: Object-Oriented Programming II

Supporting Class / C++ Lecture Notes

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

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lecture 2. Object Orientation 1 / 51

7. C++ Class and Object

Before we start looking at how we build abstract data types in Python, let's define some import terms and look at some real-world examples.

The following content is provided under a Creative Commons license. Your support

The Stack, Free Store, and Global Namespace

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

Objects. say something to express one's disapproval of or disagreement with something.

Object Oriented Programming in Python. Richard P. Muller Materials and Process Simulations Center California Institute of Technology June 1, 2000

DSC 201: Data Analysis & Visualization

C a; C b; C e; int c;

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

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace

Babu Madhav Institute of Information Technology, UTU 2015

This Week. Fields and Variables. W05 Example 1: Variables & Fields. More on Java classes. Constructors. Modifiers

OBJECT ORIENTED PROGRAMMING 7

Object Oriented Programming

COP 3330 Final Exam Review

Review 2. Classes and Subclasses

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010

OBJECT ORIENTED PROGRAMMING

Lecture 02, Fall 2018 Friday September 7

Lecture 2. Object Orientation 1 / 50

Introduction to Python! Lecture 2

CS-202 Introduction to Object Oriented Programming

CSC148: Week 1

Java: introduction to object-oriented features

Data Abstraction. Hwansoo Han

CS 1110 Final, December 8th, Question Points Score Total: 100

OBJECT ORIENTED PROGRAMMING 7

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Brief Summary of Java

Super-Classes and sub-classes

5.6.1 The Special Variable this

OBJECT ORIENTED PROGRAMMING 6

CS 1110 Final, December 8th, Question Points Score Total: 100

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

Functions Structure and Parameters behind the scenes with diagrams!

Week 2: The Clojure Language. Background Basic structure A few of the most useful facilities. A modernized Lisp. An insider's opinion

Lecture 5. Introduction to Python! Lecture 5

Introduction to Object-Oriented Programming

Chapter 1 Getting Started

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Variables and numeric types

The following content is provided under a Creative Commons license. Your support

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

CSE 12 Abstract Syntax Trees

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Lecture Notes on Programming Languages

Linked Lists. What is a Linked List?

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Chapter 6 Introduction to Defining Classes

CIS192 Python Programming

SCHEME INTERPRETER GUIDE 4

Arrays Classes & Methods, Inheritance

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

CS 112 Intro to Programming Basic OO Concepts

Positional, keyword and default arguments

At full speed with Python

Modules and scoping rules

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Assignment 4: Hashtables

9 Working with the Java Class Library

Python Interview Questions & Answers

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

1 Shyam sir JAVA Notes

PREPARING FOR PRELIM 2

Transcription:

A Crash Course in Python Part II Presented by Cuauhtémoc Carbajal ITESM CEM 1

Importing and Modules 2

Importing and Modules Use classes & functions defined in another file A Python module is a file with the same name (plus the.py extension) Like Java import, C++ include Three formats of the command: import somefile from somefile import * from somefile import classname The difference? What gets imported from the file and what name refers to it after importing 3

import import somefile Everything in somefile.py gets imported. To refer to something in the file, append the text "somefile." to the front of its name: somefile.classname.method("abc") somefile.myfunction(34) 4

import Here's an example of the method scheme in action: >>> S = 'a+b+c+' >>> x = S.replace('+', 'spam') >>> x 'aspambspamcspam' To access the same operation through the string module in Python 2.6 or higher, you need to import the module (at least once in your process) and pass in the object: >>> import string >>> y = string.replace(s, '+', 'spam') >>> y 'aspambspamcspam' 5

from import * from somefile import * Everything in somefile.py gets imported To refer to anything in the module, just use its name. Everything in the module is now in the current namespace. Take care! Using this import command can easily overwrite the definition of an existing function or variable! classname.method("abc") myfunction(34) 6

from import from somefile import classname Only the item classname in somefile.py gets imported. After importing classname, you can just use it without a module prefix. It's brought into the current namespace. Take care! Overwrites the definition of this name if already defined in the current namespace! classname.method("abc") imported myfunction(34) not imported 7

Directories for module files Where does Python look for module files? The list of directories where Python will look for the files to be imported is sys.path This is just a variable named 'path' stored inside the 'sys' module >>> import sys >>> sys.path ['/home/lucid/work/python', '/usr/bin', '/usr/lib/python2.6', ] To add a directory of your own to this list, append it to this list >>> sys.path.append('/home/lucid/work/python') 8

Object Oriented Programming in Python: Defining Classes 9

It's all objects Everything in Python is really an object. We've seen hints of this already "hello".upper() list3.append('a') dict2.keys() These look like Java or C++ method calls. New object classes can easily be defined in addition to these built-in data-types. In fact, programming in Python is typically done in an object oriented fashion. 10

Defining a Class A class is a special data type which defines how to build a certain kind of object. The class also stores some data items that are shared by all the instances of this class Instances are objects that are created which follow the definition given inside of the class Python doesn't use separate class interface definitions as in some languages You just define the class and then use it 11

Methods in Classes Define a method in a class by including function definitions within the scope of the class block There must be a special first argument self in all of method definitions which gets bound to the calling instance There is usually a special method called init in most classes We'll talk about both later 12

A simple class def: student class student: """A class representing a student """ def init (self, n, a): self.full_name = n self.age = a def get_age (self): return self.age 13

Creating and Deleting Instances 14

Instantiating Objects There is no "new" keyword as in Java. Just use the class name with ( ) notation and assign the result to a variable init serves as a constructor for the class. Usually does some initialization work The arguments passed to the class name are given to its init () method So, the init method for student is passed "Bob" and 21 and the new class instance is bound to b: b = student('bob', 21) 15

Constructor: init An init method can take any number of arguments. Like other functions or methods, the arguments can be defined with default values, making them optional to the caller. However, the first argument self in the definition of init is special 16

Self The first argument of every method is a reference to the current instance of the class By convention, we name this argument self In init, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called Similar to the keyword this in Java or C++ But Python uses self more often than Java uses this 17

Self Although you must specify self explicitly when defining the method, you don't include it when calling the method. Python passes it for you automatically Defining a method: (this code inside a class definition.) def set_age(self, num): self.age = num Calling a method: >>> x.set_age(23) 18

Deleting instances: No Need to "free" When you are done with an object, you don't have to delete or free it explicitly. Python has automatic garbage collection. Python will automatically detect when all of the references to a piece of memory have gone out of scope. Automatically frees that memory. Generally works well, few memory leaks There's also no "destructor" method for classes 19

Access to Attributes and Methods 20

Definition of student class student: """A class representing a student """ def init (self,n,a): self.full_name = n self.age = a def get_age(self): return self.age 21

Traditional Syntax for Access >>> f = student("bob Smith", 23) >>> f.full_name # Access attribute "Bob Smith" >>> f.get_age() # Access a method 23 22

Accessing unknown members Problem: Occasionally the name of an attribute or method of a class is only given at run time Solution: getattr(object_instance, string) string is a string which contains the name of an attribute or method of a class getattr(object_instance, string) returns a reference to that attribute or method 23

getattr(object_instance, string) >>> f = student("bob Smith", 23) >>> getattr(f, "full_name") "Bob Smith" >>> getattr(f, "get_age") <bound method student.get_age of < main.student instance at 0xb6599f2c>> >>> getattr(f, "get_age")() # call it 23 >>> getattr(f, "get_birthday") # Raises AttributeError student instance has no attribute 24

hasattr(object_instance,string) >>> f = student("bob Smith", 23) >>> hasattr(f, "full_name") True >>> hasattr(f, "get_age") True >>> hasattr(f, "get_birthday") False 25

Attributes 26

Two Kinds of Attributes The non-method data stored by objects are called attributes Data attributes Variable owned by a particular instance of a class Each instance has its own value for it These are the most common kind of attribute Class attributes Owned by the class as a whole All class instances share the same value for it Called "static" variables in some languages Good for (1) class-wide constants and (2) building counter of how many instances of the class have been made 27

Data Attributes Data attributes are created and initialized by an init () method. Simply assigning to a name creates the attribute Inside the class, refer to data attributes using self for example, self.full_name class teacher: "A class representing teachers." def init (self,n): self.full_name = n def print_name(self): print self.full_name 28

Class Attributes Because all instances of a class share one copy of a class attribute, when any instance changes it, the value is changed for all instances Class attributes are defined within a class definition and outside of any method Since there is one of these attributes per class and not one per instance, they're accessed via a different notation: Access class attributes using self. class.name notation -- This is just one way to do this & the safest in general. class sample: >>> a = sample() x = 23 >>> a.increment() def increment(self): >>> a. class.x self. class.x += 1 24 29

Data vs. Class Attributes class counter: overall_total = 0 # class attribute def init (self): self.my_total = 0 # data attribute def increment(self): counter.overall_total = \ counter.overall_total + 1 self.my_total = \ self.my_total + 1 >>> a = counter() >>> b = counter() >>> a.increment() >>> b.increment() >>> b.increment() >>> a.my_total 1 >>> a. class.overall_total 3 >>> b.my_total 2 >>> b. class.overall_total 3 30

Inheritance 31

Subclasses A class can extend the definition of another class Allows use (or extension ) of methods and attributes already defined in the previous one. New class: subclass. Original: parent, ancestor or superclass To define a subclass, put the name of the superclass in parentheses after the subclass's name on the first line of the definition. class Cs_student(student): Python has no 'extends' keyword like Java. Multiple inheritance is supported. 32

Redefining Methods To redefine a method of the parent class, include a new definition using the same name in the subclass. The old code won't get executed. To execute the method in the parent class in addition to new code for some method, explicitly call the parent's version of the method. parentclass.methodname(self, a, b, c) The only time you ever explicitly pass 'self' as an argument is when calling a method of an ancestor. 33

Definition of a class extending student Class Student: "A class representing a student." def init (self,n,a): self.full_name = n self.age = a def get_age(self): return self.age Class Cs_student (student): "A class extending student." def init (self,n,a,s): student. init (self,n,a) #Call init for student self.section_num = s def get_age(): #Redefines get_age method entirely print "Age: " + str(self.age) 34

Extending init Same as for redefining any other method Commonly, the ancestor's init method is executed in addition to new commands. You'll often see something like this in the init method of subclasses: parentclass. init (self, x, y) where parentclass is the name of the parent's class. 35

Special Built-In Methods and Attributes 36

Built-In Members of Classes Classes contain many methods and attributes that are included by Python even if you don't define them explicitly. Most of these methods define automatic functionality triggered by special operators or usage of that class. The built-in attributes define information that must be stored for all classes. All built-in members have double underscores around their names: init doc 37

Special Methods For example, the method repr exists for all classes, and you can always redefine it The definition of this method specifies how to turn an instance of the class into a string print f sometimes calls f. repr () to produce a string for object f If you type f at the prompt and hit ENTER, then you are also calling repr to determine what to display to the user as output 38

Special Methods Example class student:... def repr (self): return "I'm named " + self.full_name... >>> f = student("bob Smith", 23) >>> print f I'm named Bob Smith >>> f "I'm named Bob Smith" 39

Special Methods You can redefine these as well: init : The constructor for the class cmp : Define how == works for class len : Define how len( obj ) works copy : Define how to copy a class Other built-in methods allow you to give a class the ability to use [ ] notation like an array or ( ) notation like a function call 40

Special Data Items These attributes exist for all classes. doc : Variable for documentation string for class class : Variable which gives you a reference to the class from any instance of it module : Variable which gives a reference to the module in which the particular class is defined dict :The dictionary that is actually the namespace for a class (but not its superclasses) Useful: dir(x) returns a list of all methods and attributes defined for object x 41

Special Data Items Example >>> f = student("bob Smith", 23) >>> print f. doc A class representing a student. >>> f. class < class studentclass at 010B4C6 > >>> g = f. class ("Tom Jones", 34) 42

Private Data and Methods Any attribute/method with 2 leading underscores in its name (but none at the end) is private and can't be accessed outside of class Note: Names with two underscores at the beginning and the end are for built-in methods or attributes for the class Note: There is no 'protected' status in Python; so, subclasses would be unable to access these private data either. 43