James Tam Classes and Objects You will learn how to define new types of variables.

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
Object-Oriented Programming
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
References: 1. “Programming in LUA, 2 nd ed.”, Roberto Lerusalmschy Chapters (primarily) 2. “Lua Reference Manual” (included in Lua installation.
Coding Standard: General Rules 1.Always be consistent with existing code. 2.Adopt naming conventions consistent with selected framework. 3.Use the same.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
OBJECT ORIENTED PROGRAMMING (OOP) IN PYTHON David Moodie.
James Tam Advanced Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 11 Classes and Object- Oriented Programming.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
J. Michael Moore Arrays CSCE 110 From James Tam’s material.
James Tam Arrays / Lists In this section of notes you will be introduced to new type of variable that consists of other types.
James Tam Recursion You will learn the definition of recursion as well as seeing how simple recursive programs work.
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
J. Michael Moore From James Tam's material Records CSCE 110.
James Tam Programming: Part II In this section of notes you will learn about more advanced programming concepts such as looping, functions.
James Tam Records You will learn in this section of notes how to create a new, composite type, that can be composed of different types of elements.
James Tam Lists In this section of notes you will be introduced to new type of variable that consists of other types.
James Tam Advanced Composite Types You will learn in this section of notes how to create single and generic instances of non-homogeneous composite types.
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
Guide to Programming with Python
Object Oriented Software Development
CPSC 231: Classes and Objects You will learn how to define new types of variables that can have custom attributes and capabilities slide 1.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Centre for Computer Technology ICT115 Object Oriented Design and Programming Week 2 Intro to Classes Richard Salomon and Umesh Patel Centre for Information.
Chapter 10 Classes. Review of basic OOP concepts  Objects: comprised of associated DATA and ACTIONS (methods) which manipulate that data.  Instance:
Introduction to Python
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.
Tutorial 2 Variables and Objects. Working with Variables and Objects Variables (or identifiers) –Values stored in computer memory locations –Value can.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
James Tam Classes and Objects You will learn how to define new types of variables.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Classes 1 COMPSCI 105 S Principles of Computer Science.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Classes and Multiform Projects.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Python Functions.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
1 CSC241: Object Oriented Programming Lecture No 02.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Variables 1. What is a variable? Something whose value can change over time This value can change more than once over the time period (no limit!) Example:
Section 6.1 CS 106 Victor Norman IQ Unknown. The Big Q What do we get by being able to define a class?! Or Do we really need this?!
Python Let’s get started!.
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Classes and Objects, Part 1 Victor Norman CS104. “Records” In Excel, you can create rows that represent individual things, with each column representing.
Object Oriented Programming Object and Classes Lecture 3 MBY.
15 – PHP(5) Informatics Department Parahyangan Catholic University.
Linux Administration Working with the BASH Shell.
Defining Data Types in C++ Part 2: classes. Quick review of OOP Object: combination of: –data structures (describe object attributes) –functions (describe.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
CPSC 231: Classes and Objects
Python Let’s get started!.
Java Programming: Guided Learning with Early Objects
CPSC 231: Classes and Objects
Lecture VI Objects The OOP Concept Defining Classes Methods
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Variables ICS2O.
Object Oriented Programming in Python
Object Oriented Programming in java
Presentation transcript:

James Tam Classes and Objects You will learn how to define new types of variables.

James Tam Composite Types: Review Ones that you should be familiar with now: -Strings -Lists -Tuples -Dictionaries Lists can be used to track relatively simple information e.g., grades, text- based virtual worlds. It is less effective at storing more complex information (e.g., client list) – as you will see. Previous example: tracking client information firstClient = ["James Tam” "(403) ", 0] secondClient = ["Peter Griffin” "(708) ", 100]

James Tam Composite Types: Review (2) If a large number of composite types need to be tracked (e.g., many clients) then you can employ lists of lists. (This means that each list element consists of another list).

James Tam Example: List Of Lists The full online example can be found in under the name: list_of_lists.py MAX = 4 def initialize (myClients): for i in range (0, MAX, 1): temp = [(i+1), “default name”, "(111) ", 0] myClients.append(temp)

James Tam Example: Lists Of Lists (2) def display (myClients): for i in range (0, MAX, 1): print myClients[i] # MAIN myClients = [] initialize (myClients) display(myClients)

James Tam Some Drawbacks Of Using A List Which field contains what type of information? This isn’t immediately clear from looking at the program statements. temp = [(i+1), “default name”, "(111) ", 0] Is there any way to specify rules about the type of information to be stored in a field e.g., a data entry error could allow alphabetic information to be entered in the phone number field. What is this?

James Tam Classes Can be used to define a generic template for a new non- homogeneous composite type. It can label and define more complex entities than a list. This template defines what an instance or example of this new composite type would consist of but it doesn’t create an instance.

James Tam Defining A Class Format: class : name of first field = name of second field = Example: class Client: name = "default" phone = "(123) " = purchases = 0 Describes what information that would be tracked by a “Client” but doesn’t actually create a client in memory Note the convention: The first letter is capitalized.

James Tam Creating An Instance Of A Class Format: = () Example: firstClient = Client ()

James Tam Defining A Class Vs. Creating An Instance Of That Class Defining a class -A template that describes that class: how many fields, what type of information will be stored by each field, what default information will be stored in a field. Creating a class -Instances of that class (instantiations) which can take on different forms.

James Tam Accessing And Changing The Fields Format:. # Accessing value. = # Changing value Example: aClient.name = "James"

James Tam The Client List Example Implemented Using Classes The full version can be found under the name : client.py class Client: name = "default" phone = "(123) " = purchases = 0

James Tam The Client List Example Implemented Using Classes (2) def main (): firstClient = Client () firstClient.name = "James Tam" firstClient. = print firstClient.name print firstClient.phone print firstClient. print firstClient.purchases main ()

James Tam What Is The Benefit Of Defining A Class It allows new types of variables to be declared. The new type can model information about most any arbitrary entity: -Car -Movie -Your pet -A biological entity in a simulation -A ‘critter’ (e.g., monster, computer-controlled player) a video game -An ‘object’ (e.g., sword, ray gun, food) in a video game -Etc.

James Tam What Is The Benefit Of Defining A Class (2) Unlike creating a composite type by using a list a predetermined number of fields can be specified and those fields can be named. class Client: name = "default" phone = "(123) " = purchases = 0 firstClient = Client () print firstClient.middleName

James Tam What Is The Benefit Of Defining A Class (2) Unlike creating a composite type by using a list a predetermined number of fields can be specified and those fields can be named. class Client: name = "default" phone = "(123) " = purchases = 0 firstClient = Client () print firstClient.middleName There is no field by this name

James Tam Class Methods Somewhat similar to the other composite types, classes can have functions associated with them. -E.g., filename = "foo.txt" name, suffix = filename.split('.') Unlike these pre-created functions, the ones that you associate with classes can be customized to do anything that a regular function can. Functions that are associated with classes are referred to as methods.

James Tam Defining Class Methods Format: class : def (self, ): Example: class Person: name = "I have no name :(" def sayName (self): print "My name is...", self.name

James Tam Defining Class Methods: Full Example The full example can be found online under the name: person.py class Person: name = "I have no name :(" def sayName (self): print "My name is...", self.name def main (): aPerson = Person () aPerson.sayName () aPerson.name = "Big Smiley :D" aPerson.sayName () main ()

James Tam What Is The ‘Self’ Parameter When defining/call methods of a class there is always at least one parameter. This parameter is called the ‘ self ’ reference which allows an object to access it’s attributes inside it’s methods. It’s needed to distinguish the attributes of different objects of the same class. Example: bart = Person () lisa = Person () lisa.sayName () def sayName (): print "My name is...", name Whose name is this? (This won’t work)

James Tam The Self Parameter: A Complete Example The name of the full online example is: person2.py class Person: name = "I have no name :(" def sayName (self): print "My name is...", self.name def main (): lisa = Person () lisa.name = "Lisa Simpson" bart = Person () bart.name = "I'm Bart Simpson, who the h*ck are you???!!!" lisa.sayName () bart.sayName () main ()

James Tam Initializing The Attributes Of A Class Classes have a special method that can be used to initialize the starting values of a class to some specific values. This method is automatically called whenever an object is created. Format: class : def __init__ (self, ): Example: class Person: name = "" def __init__ (self): self.name = " No name " No spaces here

James Tam Full Example: Using The “ Init ” Method The name of the full online example is: init_method.py class Person: name = "" def __init__ (self): self.name = "I am the nameless bard" def main (): finder = Person () print finder.name main ()

James Tam Constructor: A Special Method Constructor method: a special method that is used when defining a class and it is automatically called when an object of that class has been created. -E.g., aPerson = Person () # This calls the constructor In Python this method is named ‘ init ’. Other languages may require a different name for the syntax but it serves the same purpose (initializing the fields of an objects as it’s being created). This method never returns any values.

James Tam Default Parameters Methods such as ‘ init ’ can be defined so that if parameters aren’t passed into them then default values can be assigned. Example: def __init__ (self, name = "I have no name"): Method calls (to ‘ init ’), both will work smiley = Person () jt = Person ("James") This method can be called either when a personalized name is given or if the name is left out.

James Tam Default Parameters: Full Example The name of the full online example is: init_method2.py class Person: name = "" def __init__ (self, name = "I have no name"): self.name = name def main (): smiley = Person () print "My name is...", smiley.name jt = Person ("James") print "My name is...", jt.name main ()

James Tam Modules: What You Should Know (Tutorial) In Python a module contains a part of a program in a separate file. In order to access a part of a program that resides in another file you must ‘ import ’ it. Example: def fun (): print "I'm fun!" File: fun.py from fun import * 1 def main (): fun () main () File: main.py 1 Import syntax: From import

James Tam Quick Review Modules: Complete Example The complete example is compressed into the file “ modules.zip ”. Extract both files into the same folder/directory and run the ‘ main ’ method (type: “ python main.py ”) > from fun import fun1, fun2 def main (): fun1 () fun2 () main ()

James Tam Quick Review Modules: Complete Example (2) > def fun1 (): print "I'm fun1!" def fun2 (): print "I'm fun2!"

James Tam Modules And Classes Class definitions are frequently contained in their own module. A common convention is to have the module (file) name match the name of the class. def Person: pass Filename: Person.py

James Tam Modules And Classes: Complete Example The complete example is compressed into the file “ modules2.zip ”. Extract both files into the same folder/directory and run the ‘ main ’ method which is in the file called “ driver.py ” (type: “ python driver.py ”) > from Foo import * def main (): aFoo = Foo () aFoo.hello () main () When importing modules containing class definitions the syntax is: From import

James Tam Modules And Classes: Complete Example (2) > class Foo: def hello (self): print "Hello! Sup?! Guten tag/morgen/aben! Buenos! Wei! Ohio! \ Shalom! Bonjour! Salaam alikum!"

James Tam You Should Now Know How to define an arbitrary composite type using a class What are the benefits of defining a composite type by using a class definition over using a list How to create instances of a class (instantiate) How to access and change the attributes (fields) of a class How to define methods/call methods of a class What is a ‘self’ parameter and why is it needed What is a constructor, when it is used and why is it used How to write a method with default parameters How to divide your program into different modules