P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

Python Objects and Classes
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Inheritance and Polymorphism CS351 – Programming Paradigms.
Writing a Class (defining a data-type). Create a new project : Project (uncheck the “Create Main Class”)
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
Review of C++ Programming Part II Sheng-Fang Huang.
Python classes: new and old. New and classic classes  With Python 2.2, classes and instances come in two flavors: old and new  New classes cleaned up.
Guide to Programming with Python
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7.
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
CPTR 124 Review for Test 1. Development Tools Editor Similar to a word processor Allows programmer to compose/save/edit source code Compiler/interpreter.
Introduction to Python III CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
By: Chris Harvey Python Classes. Namespaces A mapping from names to objects Different namespaces have different mappings Namespaces have varying lifetimes.
CSC 508 – Theory of Programming Languages, Spring, 2009 Week 3: Data Abstraction and Object Orientation.
Documentation / References Python Full Documentation – Python Quick Reference –
Built-in Data Structures in Python An Introduction.
Python Functions.
Namespace, scope, compile time activities, runtime activities When do the small integer values get stored in RAM? How did the names in the builtin namespace.
Introduction to OOP OOP = Object-Oriented Programming OOP is very simple in python but also powerful What is an object? data structure, and functions (methods)
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Object Oriented Programing (OOP)
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Head First Python: Ch 3. Files and Exceptions: Dealing with Errors Aug 26, 2013 Kyung-Bin Lim.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
More on Functions Intro to Computer Science CS1510 Dr. Sarah Diesburg.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 7: Introduction to Object- Oriented Programming in Python – Exercises Xiang Lian The University of.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
Object Oriented Programming
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Object Oriented Programming in Python: Defining Classes
Object-Oriented Programming (OOP) in Python
Functions CIS 40 – Introduction to Programming in Python
Lecture VI Objects The OOP Concept Defining Classes Methods
Creating and Deleting Instances Access to Attributes and Methods
Python Classes By Craig Pennell.
CHAPTER FIVE Classes.
Object Oriented Programming (OOP) LAB # 8
Sridhar Narayan Java Basics Sridhar Narayan
Tonga Institute of Higher Education
G. Pullaiah College of Engineering and Technology
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Java Programming with BlueJ Objectives
Python classes: new and old
Access Control Damian Gordon.
Classes and Objects Imran Rashid CTO at ManiWeber Technologies.
Python classes: new and old
CISC101 Reminders Assignment 3 due today.
def-ining a function A function as an execution control structure
© Sangeeta M Chauhan, Gwalior
Presentation transcript:

P YTHON ’ S C LASSES Ian Wynyard

I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that can be executed by invoking the class in a main method. An object constructed by a class is called an instance of that class Methods can be invoked upon instances of their associated class

P REDEFINED C LASS A TTRIBUTES AttributeTypeRead/Writ e Description __dict__dictionaryR/WClass name space __name__stringR/OName of the class __bases__tuple of classesR/OClass inheritance __doc__string OR noneR/WDocumentation string __module__StringR/WDefining module All classes in python have these 5 attributes Python supports class inheritance Python can have private class variables like Java Python handles objects with individuality with name spaces mapping class names to objects within a shared scope Multiple names can identify the same object (this is part of modules)

S COPES AND N AMESPACES – T UTORIAL E X. def scope_test(): def do_local(): // Default scope spam = "local spam“ def do_nonlocal(): nonlocal spam spam = "nonlocal spam“ def do_global(): global spam spam = "global spam“ spam = "test spam“ do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test() print("In global scope:", spam)

D EFINING A C LASS Classes are defined in the following format: class ClassName: “Here is an explanation of the class” pass In Python the convention is the capitalize the name of the class It is also conventional to provide a brief explanation of the class The pass statement tells the interpreter to do nothing and proceed. It is removed when arguments are entered

I NSTANCE C ONSTRUCTION Instances are constructed in the following format: class Dog: “Is Wolfie ok? Wolfie is fine dear.” pass Then an instance is constructed by calling the class object: Max = Dog() An instance of the class Dog has been constructed. The name of the instance is Max. To access the member of an instance of a class write.

M ETHODS Instances are constructed in the following format: class WinkWink: def NudgeNudge (self, x): self.x = x def SayNoMore(self): print self.x pass A method is a function within a class. This example has 2. In this example nothing would happen until an instance of WinkWink was declared and SayNoMore() was invoked

I NVOKING M ETHODS Methods are invoked with the following declaration: KnowWhatIMean= WinkWink() KnowWhatIMean.NudgeNudge(“Wife”) KnowWhatIMean.SayNoMore() This will output Wife You can also call a method on an arbitrary object like this: WinkWink.NudgeNudge(f, ‘Wife”) WinkWink.SayNoMore(f)

D YNAMIC C LASS S TRUCTURE The members of a Python class can change during runtime This is different from C and Java We can delete members inruntime and return associated errors KnowWhatIMean= WinkWink() KnowWhatIMean.NudgeNudge(“Wife”) del KnowWhatIMean.x KnowWhatIMean.SayNoMore() This will output return the following error Traceback (most recent call last): File " ", line 1, in ? File " ", line 5, in bar AttributeError: WinkWink instance has no attribute 'x'

D YNAMIC C LASS S TRUCTURE – C ONT. The definition of a Python class can change during execution Parrot.dead = 10 NorwegianBlue = Parrot() NorwegianBlue.dead Output:10 Here we created an arbitrary value “dead” and then added it to a new member Norwegian Blue

C LASS D ICTIONARIES Viewing dictionaries: vars(Parrot) Output: {‘dead’: 10, “pining”:, '__module__': '__main__', '__doc__': None} These are the members of the Parrot class definition. If values are then assigned to members of the class, then the dictionary for the member changes, not the class.

C HANGING I NSTANCE D ICTIONARIES Let’s change something NorwegianBlue.pining vars(NorwegianBlue) {‘x’: 6} This shows the dictionary for NorwegianBlue NorwegianBlue.y = 18 vars(NorwegianBlue) {‘y’: 18, ‘x’: 6} The most recent change appears first The class dictionary doesn’t change in this case

C HANGING C LASS D ICTIONARIES Let’s change something else NorwegianBlue.__dict__ {‘y’: 18, ‘x’: 6} This shows the members dictionary for the class Parrot relative to NorwegianBlue NorwegianBlue.__dict__[‘z’] = 8 NorwegianBlue.z Output: 8 This let us alter and insert a new key-value pair into NorwegianBlue.__dict__. This is the same effect as changing the members of NorwegianBlue

N EW S TYLE C LASSES Introduced in Python 2.2 A class that has a built-in as its base Old classes were of the type instance New style classes return the same thing as x.__class__ as their type Old classes are not in Python 3, only new style Old class OldSchool: def __init__(self): Pass New class NewSchool(object): def __init__(self): Pass

N EW S TYLE C LASSES – D IFFERENCES Properties can be set with decorator class OldSchool: def __init__(self): self.__frank = “The def frank(self): return def frank(self, frank): self.__frank = frank Static methods can be declared with decorator class def DarkKnight(): print “My parents are dead!”

THE END!!!!! Spam Spam Spam Spam Spam Spam………