SlideShare a Scribd company logo
CPSC 231:
Classes and Objects
You will learn how to define new types
of variables that can have custom
attributes and capabilities
slide 1
Some Drawbacks Of Using A List
• Which field contains what type of information? This isn’t
immediately clear from looking at the program statements.
client = [“xxxxxxxxxxxxxxx",
“0000000000",
“xxxxxxxxx",
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 (e.g., 1-800-BUY-NOWW) to be entered
in the phone number field.
The parts of a composite list can
be accessed via [index] but they
cannot be labeled (what do these
fields store?)
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 (example) of this new
composite type would consist of but it doesn’t create an
instance.
Copyright information unknown
James Tam
Classes Define A Composite Type
• The class definition specifies the type of information (called
“attributes”) that each instance (example) tracks.
Name:
Phone:
Email:
Purchases:
Name:
Phone:
Email:
Purchases:
Name:
Phone:
Email:
Purchases:
Defining A Class1
• Format:
class <Name of the class>:
name of first field = <default value>
name of second field = <default value>
• Example:
class Client:
name = "default"
phone = "(123)456-7890"
email = "foo@bar.com"
purchases = 0
Describes what information
that would be tracked by a
“Client” but doesn’t actually
create a client variable
Note the convention: The
first letter is capitalized.
Contrast this with a list definition of a client
client = [“xxxxxxxxxxxxxxx",
“0000000000",
“xxxxxxxxx",
0]
1 Although this structure isn’t commonly used in Python it is common to many other programming languages: Java, C++
Creating An Instance Of A Class
• Creating an actual instance (instance = object) is referred to as
• Format:
<reference name> = <name of class>()
• Example:
firstClient = Client()
instantiation
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 an object
– Instances of that class (during
instantiation) which can take
on different forms.
Image copyright unknown
Accessing And Changing The Attributes
•Format:
<reference name>.<field name> # Accessing
value
<reference name>.<field name> = <value> # Changing
value
•Example:
aClient.name = "James"
The Client List Example Implemented Using
Classes And Objects
• Name of the online example: client.py
class Client:
name = "default"
phone = "(123)456-7890"
email = "foo@bar.com"
purchases = 0
The Client List Example Implemented
Using Classes (2)
def main():
firstClient = Client()
firstClient.name = "James Tam"
firstClient.email = "tam@ucalgary.ca"
print(firstClient.name)
print(firstClient.phone)
print(firstClient.email)
print(firstClient.purchases)
main()
name = "default"
phone = "(123)456-
7890"
email = "foo@bar.com"
purchases = 0
name = "James Tam"
email =
"tam@ucalgary.ca"
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 bacteria or virus in a medical simulation
–A ‘critter’ (e.g., monster, computer-controlled player) a video game
–An ‘object’ (e.g., sword, ray gun, food, treasure) in a video game
–A member of a website (e.g., a social network user could have
attributes to specify the person’s: images, videos, links, comments and
other posts associated with the ‘profile’ object).
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)456-7890"
email = "foo@bar.com"
purchases = 0
firstClient = Client ()
print(firstClient.middleName) # Error: no such field
defined
Classes Have Attributes
ATTRIBUTES
Name:
Phone:
Email:
Purchases:
BEHAVIORS
Open account
Buy investments
Sell investments
Close account
Image of James curtesy of James
But Also Behaviors
Class Methods (“Behaviors”)
• Functions: not tied to a composite type or object
– The call is ‘stand alone’, just name of function
– E.g.,
– print(), input()
• Methods: must be called through an instance of a composite1
.
– 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.
String Method operating on
that string
1 Not all composites have methods e.g., arrays in ‘C’ are a composite but don’t have methods
James Tam
Defining Class Methods
Format:
class <classname>:
def <method name> (self, <other parameters>):
<method body>
Example:
class Person:
name = "I have no name :("
def sayName (self):
print ("My name is...", self.name)
Unlike functions, every
method of a class must
have the ‘self’
parameter (more on this
later)
When the attributes are
accessed inside the
methods of a class they
MUST be preceded by the
suffix “.self”
James Tam
Defining Class Methods: Full Example
• Name of the online example: person1.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
• Reminder: When defining/calling methods of a class there is
always at least one parameter.
• This parameter is called the ‘self’ reference which allows an
object to access attributes inside its methods.
• ‘Self’ 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
• Name of the online example: 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, pleased to meet you."
bart = Person()
bart.name = "I'm Bart Simpson, who the hek are
you???!!!"
lisa.sayName()
bart.sayName()
main()
“The Simpsons”  Fox
James Tam
Recap: Accessing Attributes & Methods
• Inside the class definition (inside the body of the class
methods)
– Preface the attribute or method using the ‘self’ reference
class Person:
name = "No-name"
def sayName(self):
print("My name is...", self.name)
• Outside the class definition
– Preface the attribute or method using the name of the reference used
when creating the object.
def main():
lisa = Person()
bart = Person()
lisa.name = "Lisa Simpson, pleased to meet you."
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 <Class name>:
def __init__(self, <other parameters>):
<body of the method>
• Example:
class Person:
name = ""
def __init__(self):
self.name = "No name"
No spaces here
This design
approach is
consistent with
many
languages
James Tam
Initializing The Attributes Of A Class
• Because the ‘init()’ method is a method it can also be called with
parameters which are then used to initialize the attributes.
• Example:
# Attribute is set to a default in the class definition and then
the # attribute can be set to a non-default value in the init()
method.
# (Not standard Python but a common approach with many languages)
class Person
name = "Default name" # Create attribute here
def __init___(self, aName):
self.name = aName
–OR
# Create the attribute in the init() method. (Approach often used
in
# Python).
class Person
def __init___(self, aName):
self.name = aName # Create attribute here
James Tam
Full Example: Using The “Init()” Method
• The name of the online example: init_method1.py
class Person:
name = "Nameless bard"
def __init__(self, aName):
self.name = aName
def main():
aPerson = Person("Finder Wyvernspur")
print(aPerson.name)
main()
“Nameless bard” & “Finder Wyvernspur”  Wizards of the Coast (April 24, 2012)
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
object as it’s being created).
• This method should never have a return statement that returns
a value.
– Should be (if return is needed) “return”
– Never return a type e.g., return(12)
James Tam
Objects Employ References
aPerson = Person()
Calls the constructor
and creates an object
Creates the
reference
variable
Assign the address
of the object into
the reference
James Tam
Objects Employ References (2)
• Similar to lists, objects are accessed through a reference.
• The reference and the object are two separate memory
locations.
• Name of the online example: objectReference.py
class Person:
age = 0
name = "none"
def __init__(self,newAge,newName):
self.age = newAge
self.name = newName
def displayAge(aPerson):
print("%s age %d" %(aPerson.name,aPerson.age))
James Tam
Objects Employ References (3)
def start():
person1 =
Person(13,"Person2")
person2 = person1
displayAge(person1)
displayAge(person2)
print()
start()
Age: 13
Name: Person2
Address = 1000
person1 @=1000
person2 @=1000
James Tam
Objects Employ References (2)
def start():
person1 =
Person(13,"Person2")
person2 = person1
displayAge(person1)
displayAge(person2)
print()
person1 =
Person(888,"Person1")
displayAge(person1)
displayAge(person2)
start()
Age: 13
Name: Person2
Address = 1000
person1 @=1000
person2 @=1000
Age: 888
Name: Person1
Address = 2000
@=2000
James Tam
Default Parameters
• Similar to other methods, ‘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
• Name of the online example: 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()
Modules: Dividing Up A Large Program
• Module: In Python a module contains a part of a program in a
separate file (module name matches the file name).
• In order to access a part of a program that resides in another
file you must ‘import’ it.1
• Example:
def fun ():
print("I'm fun!")
File:
functions.py import functions
def main():
functions.fun()
main()
File: driver.py
1 Import syntax:
From <file name> import <function names> # Import some functions
From <file name> import * # Import all functions
OR
import <file name> # Import only module/file
James Tam
Function Modules: Complete Example
• Subdirectory name with all the files for this example:
modules1
– Run the program method type: “python driver.py”
<< In module file1.py >>
def fun1():
print("I'm fun1!")
def fun2():
print("I'm fun2!")
<< In module file2.py >>
def fun3():
print("I'm fun3!")
James Tam
Modules: Complete Example (2)
<< In file driver.py >>
from file1 import fun1, fun2 #Import file name, function
name
import file2 #Imports only file name
def start():
fun1()
fun2()
file2.fun3()
main ()
Note the difference in how
fun1 & fun2 vs. fun3 are called
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.
• To use the code of class Person from another file module you
must include an import:
from <filename> import <class name>
from Person import Person
class Person:
def fun1(self):
print(“fun1”)
def fun2 (self):
print(“fun2”)
Filename: Person.py
James Tam
Modules And Classes: Complete Example
• Subdirectory name with all the files for this example:
modules2
– To run the program type: “python Driver.py”
<< File Driver.py >>
from Greetings import *
def start():
aGreeting = Greeting()
aGreeting.sayGreeting()
start()
When importing modules containing class definitions the syntax is (star ‘*’ imports everything):
From <filename> import <classes to be used in this module>
James Tam
Modules And Classes: Complete Example (2)
<< File Greetings.py >>
class Greetings:
def sayGreeting(self):
print("Hello! Hallo! Sup?! Guten tag/morgen/aben! Buenos!
Wei! 
Konichiwa! Shalom! Bonjour! Salaam alikum!
Kamostaka?")
James Tam
Calling A Classes’ Method Inside Another Method Of
The Same Class
• Similar to how attributes must be preceded by the keyword
‘self’ before they can be accessed so must the classes’
methods:
• Example:
class Bar:
x = 1
def fun1(self):
print(self.x) # Accessing attribute ‘x’
def fun2(self):
self.fun1() # Calling method ‘fun1’
James Tam
Naming The Starting Module
• Recall: The function that starts a program (first one called)
should have a good self-explanatory name e.g., “start()” or
follow common convention e.g., “main()”
• Similarly the file module that contains the ‘start()’ or
‘main()’ function should be given an appropriate name e.g.,
“Driver.py” (it’s the ‘driver’ of the program or the starting
point)
def start():
#Instructions
start()
Filename: “Driver.py”
James Tam
Complete Example: Accessing Attributes And
Methods: Person Module
• Subdirectory name with all the files for this example:
modules3
– To start the program run the ‘start’ method (type: “python
Driver.py” because ‘start()’ resides in the ‘Driver’ module.
<< Person.py >>
class Person:
name = "Not named yet"
age = 0
def __init__(self,newName,newAge):
self.name = newName
self.age = newAge
James Tam
Complete Example: Accessing Attributes And Methods:
Person Module (2)
def haveBirthday(self):
print("Happy Birthday!")
self.mature()
def mature(self):
self.age = self.age + 1
James Tam
Complete Example: Accessing Attributes And Methods:
The “Driver” Module
<< Driver.py >>
from Person import Person
def main():
aPerson = Person("Cartman",8)
print("%s is %d." %(aPerson.name,aPerson.age))
aPerson.haveBirthday()
print("%s is %d." %(aPerson.name,aPerson.age))
main()
def
__init__(self,newName,newAge):
self.name = newName
self.age = newAge
def haveBirthday(self)
print("Happy
Birthday!")
self.mature()
def mature(self):
self.age = self.age +
1
After This Section 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 the ‘self’ parameter and why is it needed
• What is a constructor (__init__ in Python), 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
James Tam
Copyright Notification
• “Unless otherwise indicated, all images in this presentation
are used with permission from Microsoft.”
slide 42
Ad

Recommended

Lecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
Introduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Python3
Python3
Ruchika Sinha
 
Module-5-Classes and Objects for Python Programming.pptx
Module-5-Classes and Objects for Python Programming.pptx
YogeshKumarKJMIT
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptx
santoshkumar811204
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Unit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
Python programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Unit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
thuy27042005thieu
 
Python_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptx
Koteswari Kasireddy
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
Koteswari Kasireddy
 
Object oriented programming with python
Object oriented programming with python
Arslan Arshad
 
Python advance
Python advance
Mukul Kirti Verma
 
Object Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
slides11-objects_and_classes in python.pptx
slides11-objects_and_classes in python.pptx
debasisdas225831
 
Python Lecture 13
Python Lecture 13
Inzamam Baig
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Python unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
Python_Unit_3.pdf
Python_Unit_3.pdf
alaparthi
 
object oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
Regex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overloding
sangumanikesh
 
OOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptx
uzairrrfr
 
Programming in C in I scheme MSBTE 1st Year.pptx
Programming in C in I scheme MSBTE 1st Year.pptx
malikliyaqathusain
 
programming in C in I scheme arrays.pptx
programming in C in I scheme arrays.pptx
malikliyaqathusain
 

More Related Content

Similar to what is class in C++ and classes_objects.ppt (20)

جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
Unit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
Python programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Unit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
thuy27042005thieu
 
Python_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptx
Koteswari Kasireddy
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
Koteswari Kasireddy
 
Object oriented programming with python
Object oriented programming with python
Arslan Arshad
 
Python advance
Python advance
Mukul Kirti Verma
 
Object Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
slides11-objects_and_classes in python.pptx
slides11-objects_and_classes in python.pptx
debasisdas225831
 
Python Lecture 13
Python Lecture 13
Inzamam Baig
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Python unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
Python_Unit_3.pdf
Python_Unit_3.pdf
alaparthi
 
object oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
Regex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overloding
sangumanikesh
 
OOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptx
uzairrrfr
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Unit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
thuy27042005thieu
 
Python_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptx
Koteswari Kasireddy
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
Koteswari Kasireddy
 
Object oriented programming with python
Object oriented programming with python
Arslan Arshad
 
Object Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
slides11-objects_and_classes in python.pptx
slides11-objects_and_classes in python.pptx
debasisdas225831
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Python unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
Python_Unit_3.pdf
Python_Unit_3.pdf
alaparthi
 
object oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
Regex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overloding
sangumanikesh
 
OOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptx
uzairrrfr
 

More from malikliyaqathusain (11)

Programming in C in I scheme MSBTE 1st Year.pptx
Programming in C in I scheme MSBTE 1st Year.pptx
malikliyaqathusain
 
programming in C in I scheme arrays.pptx
programming in C in I scheme arrays.pptx
malikliyaqathusain
 
Programming in C Chapter-3 for I - scheme
Programming in C Chapter-3 for I - scheme
malikliyaqathusain
 
Programming in C Chapter-2 for I - scheme
Programming in C Chapter-2 for I - scheme
malikliyaqathusain
 
swk-340-powerpoint-chapter-1-introduction-to-research_rdecarlotextbook.pptx
swk-340-powerpoint-chapter-1-introduction-to-research_rdecarlotextbook.pptx
malikliyaqathusain
 
problem discovery presentation for research
problem discovery presentation for research
malikliyaqathusain
 
chapter number, introduction to research
chapter number, introduction to research
malikliyaqathusain
 
chapter number, introduction to research
chapter number, introduction to research
malikliyaqathusain
 
chapter number, introduction to research
chapter number, introduction to research
malikliyaqathusain
 
chapter number, introduction to research
chapter number, introduction to research
malikliyaqathusain
 
PRESENTATION ON THE TASK PLANNING AND MANAGEMENT.ppt
PRESENTATION ON THE TASK PLANNING AND MANAGEMENT.ppt
malikliyaqathusain
 
Programming in C in I scheme MSBTE 1st Year.pptx
Programming in C in I scheme MSBTE 1st Year.pptx
malikliyaqathusain
 
programming in C in I scheme arrays.pptx
programming in C in I scheme arrays.pptx
malikliyaqathusain
 
Programming in C Chapter-3 for I - scheme
Programming in C Chapter-3 for I - scheme
malikliyaqathusain
 
Programming in C Chapter-2 for I - scheme
Programming in C Chapter-2 for I - scheme
malikliyaqathusain
 
swk-340-powerpoint-chapter-1-introduction-to-research_rdecarlotextbook.pptx
swk-340-powerpoint-chapter-1-introduction-to-research_rdecarlotextbook.pptx
malikliyaqathusain
 
problem discovery presentation for research
problem discovery presentation for research
malikliyaqathusain
 
chapter number, introduction to research
chapter number, introduction to research
malikliyaqathusain
 
chapter number, introduction to research
chapter number, introduction to research
malikliyaqathusain
 
chapter number, introduction to research
chapter number, introduction to research
malikliyaqathusain
 
chapter number, introduction to research
chapter number, introduction to research
malikliyaqathusain
 
PRESENTATION ON THE TASK PLANNING AND MANAGEMENT.ppt
PRESENTATION ON THE TASK PLANNING AND MANAGEMENT.ppt
malikliyaqathusain
 
Ad

Recently uploaded (20)

NEW Strengthened Senior High School Gen Math.pptx
NEW Strengthened Senior High School Gen Math.pptx
DaryllWhere
 
retina_biometrics ruet rajshahi bangdesh.pptx
retina_biometrics ruet rajshahi bangdesh.pptx
MdRakibulIslam697135
 
machine learning is a advance technology
machine learning is a advance technology
ynancy893
 
Deep Learning for Image Processing on 16 June 2025 MITS.pptx
Deep Learning for Image Processing on 16 June 2025 MITS.pptx
resming1
 
special_edition_using_visual_foxpro_6.pdf
special_edition_using_visual_foxpro_6.pdf
Shabista Imam
 
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
Solar thermal – Flat plate and concentrating collectors .pptx
Solar thermal – Flat plate and concentrating collectors .pptx
jdaniabraham1
 
60 Years and Beyond eBook 1234567891.pdf
60 Years and Beyond eBook 1234567891.pdf
waseemalazzeh
 
Introduction to sensing and Week-1.pptx
Introduction to sensing and Week-1.pptx
KNaveenKumarECE
 
Structured Programming with C++ :: Kjell Backman
Structured Programming with C++ :: Kjell Backman
Shabista Imam
 
Complete guidance book of Asp.Net Web API
Complete guidance book of Asp.Net Web API
Shabista Imam
 
Industry 4.o the fourth revolutionWeek-2.pptx
Industry 4.o the fourth revolutionWeek-2.pptx
KNaveenKumarECE
 
LECTURE 7 COMPUTATIONS OF LEVELING DATA APRIL 2025.pptx
LECTURE 7 COMPUTATIONS OF LEVELING DATA APRIL 2025.pptx
rr22001247
 
Proposal for folders structure division in projects.pdf
Proposal for folders structure division in projects.pdf
Mohamed Ahmed
 
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
Machine Learning - Classification Algorithms
Machine Learning - Classification Algorithms
resming1
 
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Mark Billinghurst
 
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
Unit III_One Dimensional Consolidation theory
Unit III_One Dimensional Consolidation theory
saravananr808639
 
System design handwritten notes guidance
System design handwritten notes guidance
Shabista Imam
 
NEW Strengthened Senior High School Gen Math.pptx
NEW Strengthened Senior High School Gen Math.pptx
DaryllWhere
 
retina_biometrics ruet rajshahi bangdesh.pptx
retina_biometrics ruet rajshahi bangdesh.pptx
MdRakibulIslam697135
 
machine learning is a advance technology
machine learning is a advance technology
ynancy893
 
Deep Learning for Image Processing on 16 June 2025 MITS.pptx
Deep Learning for Image Processing on 16 June 2025 MITS.pptx
resming1
 
special_edition_using_visual_foxpro_6.pdf
special_edition_using_visual_foxpro_6.pdf
Shabista Imam
 
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
Solar thermal – Flat plate and concentrating collectors .pptx
Solar thermal – Flat plate and concentrating collectors .pptx
jdaniabraham1
 
60 Years and Beyond eBook 1234567891.pdf
60 Years and Beyond eBook 1234567891.pdf
waseemalazzeh
 
Introduction to sensing and Week-1.pptx
Introduction to sensing and Week-1.pptx
KNaveenKumarECE
 
Structured Programming with C++ :: Kjell Backman
Structured Programming with C++ :: Kjell Backman
Shabista Imam
 
Complete guidance book of Asp.Net Web API
Complete guidance book of Asp.Net Web API
Shabista Imam
 
Industry 4.o the fourth revolutionWeek-2.pptx
Industry 4.o the fourth revolutionWeek-2.pptx
KNaveenKumarECE
 
LECTURE 7 COMPUTATIONS OF LEVELING DATA APRIL 2025.pptx
LECTURE 7 COMPUTATIONS OF LEVELING DATA APRIL 2025.pptx
rr22001247
 
Proposal for folders structure division in projects.pdf
Proposal for folders structure division in projects.pdf
Mohamed Ahmed
 
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
Machine Learning - Classification Algorithms
Machine Learning - Classification Algorithms
resming1
 
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Rapid Prototyping for XR: Lecture 1 Introduction to Prototyping
Mark Billinghurst
 
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
Unit III_One Dimensional Consolidation theory
Unit III_One Dimensional Consolidation theory
saravananr808639
 
System design handwritten notes guidance
System design handwritten notes guidance
Shabista Imam
 
Ad

what is class in C++ and classes_objects.ppt

  • 1. CPSC 231: Classes and Objects You will learn how to define new types of variables that can have custom attributes and capabilities slide 1
  • 2. Some Drawbacks Of Using A List • Which field contains what type of information? This isn’t immediately clear from looking at the program statements. client = [“xxxxxxxxxxxxxxx", “0000000000", “xxxxxxxxx", 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 (e.g., 1-800-BUY-NOWW) to be entered in the phone number field. The parts of a composite list can be accessed via [index] but they cannot be labeled (what do these fields store?)
  • 3. 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 (example) of this new composite type would consist of but it doesn’t create an instance. Copyright information unknown
  • 4. James Tam Classes Define A Composite Type • The class definition specifies the type of information (called “attributes”) that each instance (example) tracks. Name: Phone: Email: Purchases: Name: Phone: Email: Purchases: Name: Phone: Email: Purchases:
  • 5. Defining A Class1 • Format: class <Name of the class>: name of first field = <default value> name of second field = <default value> • Example: class Client: name = "default" phone = "(123)456-7890" email = "[email protected]" purchases = 0 Describes what information that would be tracked by a “Client” but doesn’t actually create a client variable Note the convention: The first letter is capitalized. Contrast this with a list definition of a client client = [“xxxxxxxxxxxxxxx", “0000000000", “xxxxxxxxx", 0] 1 Although this structure isn’t commonly used in Python it is common to many other programming languages: Java, C++
  • 6. Creating An Instance Of A Class • Creating an actual instance (instance = object) is referred to as • Format: <reference name> = <name of class>() • Example: firstClient = Client() instantiation
  • 7. 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 an object – Instances of that class (during instantiation) which can take on different forms. Image copyright unknown
  • 8. Accessing And Changing The Attributes •Format: <reference name>.<field name> # Accessing value <reference name>.<field name> = <value> # Changing value •Example: aClient.name = "James"
  • 9. The Client List Example Implemented Using Classes And Objects • Name of the online example: client.py class Client: name = "default" phone = "(123)456-7890" email = "[email protected]" purchases = 0
  • 10. The Client List Example Implemented Using Classes (2) def main(): firstClient = Client() firstClient.name = "James Tam" firstClient.email = "[email protected]" print(firstClient.name) print(firstClient.phone) print(firstClient.email) print(firstClient.purchases) main() name = "default" phone = "(123)456- 7890" email = "[email protected]" purchases = 0 name = "James Tam" email = "[email protected]"
  • 11. 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 bacteria or virus in a medical simulation –A ‘critter’ (e.g., monster, computer-controlled player) a video game –An ‘object’ (e.g., sword, ray gun, food, treasure) in a video game –A member of a website (e.g., a social network user could have attributes to specify the person’s: images, videos, links, comments and other posts associated with the ‘profile’ object).
  • 12. 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)456-7890" email = "[email protected]" purchases = 0 firstClient = Client () print(firstClient.middleName) # Error: no such field defined
  • 13. Classes Have Attributes ATTRIBUTES Name: Phone: Email: Purchases: BEHAVIORS Open account Buy investments Sell investments Close account Image of James curtesy of James But Also Behaviors
  • 14. Class Methods (“Behaviors”) • Functions: not tied to a composite type or object – The call is ‘stand alone’, just name of function – E.g., – print(), input() • Methods: must be called through an instance of a composite1 . – 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. String Method operating on that string 1 Not all composites have methods e.g., arrays in ‘C’ are a composite but don’t have methods
  • 15. James Tam Defining Class Methods Format: class <classname>: def <method name> (self, <other parameters>): <method body> Example: class Person: name = "I have no name :(" def sayName (self): print ("My name is...", self.name) Unlike functions, every method of a class must have the ‘self’ parameter (more on this later) When the attributes are accessed inside the methods of a class they MUST be preceded by the suffix “.self”
  • 16. James Tam Defining Class Methods: Full Example • Name of the online example: person1.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()
  • 17. James Tam What Is The ‘Self’ Parameter • Reminder: When defining/calling methods of a class there is always at least one parameter. • This parameter is called the ‘self’ reference which allows an object to access attributes inside its methods. • ‘Self’ 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)
  • 18. James Tam The Self Parameter: A Complete Example • Name of the online example: 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, pleased to meet you." bart = Person() bart.name = "I'm Bart Simpson, who the hek are you???!!!" lisa.sayName() bart.sayName() main() “The Simpsons”  Fox
  • 19. James Tam Recap: Accessing Attributes & Methods • Inside the class definition (inside the body of the class methods) – Preface the attribute or method using the ‘self’ reference class Person: name = "No-name" def sayName(self): print("My name is...", self.name) • Outside the class definition – Preface the attribute or method using the name of the reference used when creating the object. def main(): lisa = Person() bart = Person() lisa.name = "Lisa Simpson, pleased to meet you."
  • 20. 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 <Class name>: def __init__(self, <other parameters>): <body of the method> • Example: class Person: name = "" def __init__(self): self.name = "No name" No spaces here This design approach is consistent with many languages
  • 21. James Tam Initializing The Attributes Of A Class • Because the ‘init()’ method is a method it can also be called with parameters which are then used to initialize the attributes. • Example: # Attribute is set to a default in the class definition and then the # attribute can be set to a non-default value in the init() method. # (Not standard Python but a common approach with many languages) class Person name = "Default name" # Create attribute here def __init___(self, aName): self.name = aName –OR # Create the attribute in the init() method. (Approach often used in # Python). class Person def __init___(self, aName): self.name = aName # Create attribute here
  • 22. James Tam Full Example: Using The “Init()” Method • The name of the online example: init_method1.py class Person: name = "Nameless bard" def __init__(self, aName): self.name = aName def main(): aPerson = Person("Finder Wyvernspur") print(aPerson.name) main() “Nameless bard” & “Finder Wyvernspur”  Wizards of the Coast (April 24, 2012)
  • 23. 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 object as it’s being created). • This method should never have a return statement that returns a value. – Should be (if return is needed) “return” – Never return a type e.g., return(12)
  • 24. James Tam Objects Employ References aPerson = Person() Calls the constructor and creates an object Creates the reference variable Assign the address of the object into the reference
  • 25. James Tam Objects Employ References (2) • Similar to lists, objects are accessed through a reference. • The reference and the object are two separate memory locations. • Name of the online example: objectReference.py class Person: age = 0 name = "none" def __init__(self,newAge,newName): self.age = newAge self.name = newName def displayAge(aPerson): print("%s age %d" %(aPerson.name,aPerson.age))
  • 26. James Tam Objects Employ References (3) def start(): person1 = Person(13,"Person2") person2 = person1 displayAge(person1) displayAge(person2) print() start() Age: 13 Name: Person2 Address = 1000 person1 @=1000 person2 @=1000
  • 27. James Tam Objects Employ References (2) def start(): person1 = Person(13,"Person2") person2 = person1 displayAge(person1) displayAge(person2) print() person1 = Person(888,"Person1") displayAge(person1) displayAge(person2) start() Age: 13 Name: Person2 Address = 1000 person1 @=1000 person2 @=1000 Age: 888 Name: Person1 Address = 2000 @=2000
  • 28. James Tam Default Parameters • Similar to other methods, ‘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.
  • 29. James Tam Default Parameters: Full Example • Name of the online example: 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()
  • 30. Modules: Dividing Up A Large Program • Module: In Python a module contains a part of a program in a separate file (module name matches the file name). • In order to access a part of a program that resides in another file you must ‘import’ it.1 • Example: def fun (): print("I'm fun!") File: functions.py import functions def main(): functions.fun() main() File: driver.py 1 Import syntax: From <file name> import <function names> # Import some functions From <file name> import * # Import all functions OR import <file name> # Import only module/file
  • 31. James Tam Function Modules: Complete Example • Subdirectory name with all the files for this example: modules1 – Run the program method type: “python driver.py” << In module file1.py >> def fun1(): print("I'm fun1!") def fun2(): print("I'm fun2!") << In module file2.py >> def fun3(): print("I'm fun3!")
  • 32. James Tam Modules: Complete Example (2) << In file driver.py >> from file1 import fun1, fun2 #Import file name, function name import file2 #Imports only file name def start(): fun1() fun2() file2.fun3() main () Note the difference in how fun1 & fun2 vs. fun3 are called
  • 33. 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. • To use the code of class Person from another file module you must include an import: from <filename> import <class name> from Person import Person class Person: def fun1(self): print(“fun1”) def fun2 (self): print(“fun2”) Filename: Person.py
  • 34. James Tam Modules And Classes: Complete Example • Subdirectory name with all the files for this example: modules2 – To run the program type: “python Driver.py” << File Driver.py >> from Greetings import * def start(): aGreeting = Greeting() aGreeting.sayGreeting() start() When importing modules containing class definitions the syntax is (star ‘*’ imports everything): From <filename> import <classes to be used in this module>
  • 35. James Tam Modules And Classes: Complete Example (2) << File Greetings.py >> class Greetings: def sayGreeting(self): print("Hello! Hallo! Sup?! Guten tag/morgen/aben! Buenos! Wei! Konichiwa! Shalom! Bonjour! Salaam alikum! Kamostaka?")
  • 36. James Tam Calling A Classes’ Method Inside Another Method Of The Same Class • Similar to how attributes must be preceded by the keyword ‘self’ before they can be accessed so must the classes’ methods: • Example: class Bar: x = 1 def fun1(self): print(self.x) # Accessing attribute ‘x’ def fun2(self): self.fun1() # Calling method ‘fun1’
  • 37. James Tam Naming The Starting Module • Recall: The function that starts a program (first one called) should have a good self-explanatory name e.g., “start()” or follow common convention e.g., “main()” • Similarly the file module that contains the ‘start()’ or ‘main()’ function should be given an appropriate name e.g., “Driver.py” (it’s the ‘driver’ of the program or the starting point) def start(): #Instructions start() Filename: “Driver.py”
  • 38. James Tam Complete Example: Accessing Attributes And Methods: Person Module • Subdirectory name with all the files for this example: modules3 – To start the program run the ‘start’ method (type: “python Driver.py” because ‘start()’ resides in the ‘Driver’ module. << Person.py >> class Person: name = "Not named yet" age = 0 def __init__(self,newName,newAge): self.name = newName self.age = newAge
  • 39. James Tam Complete Example: Accessing Attributes And Methods: Person Module (2) def haveBirthday(self): print("Happy Birthday!") self.mature() def mature(self): self.age = self.age + 1
  • 40. James Tam Complete Example: Accessing Attributes And Methods: The “Driver” Module << Driver.py >> from Person import Person def main(): aPerson = Person("Cartman",8) print("%s is %d." %(aPerson.name,aPerson.age)) aPerson.haveBirthday() print("%s is %d." %(aPerson.name,aPerson.age)) main() def __init__(self,newName,newAge): self.name = newName self.age = newAge def haveBirthday(self) print("Happy Birthday!") self.mature() def mature(self): self.age = self.age + 1
  • 41. After This Section 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 the ‘self’ parameter and why is it needed • What is a constructor (__init__ in Python), 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
  • 42. James Tam Copyright Notification • “Unless otherwise indicated, all images in this presentation are used with permission from Microsoft.” slide 42

Editor's Notes

  • #5: List definition The fields are unnamed, less clear
  • #6: Class variable is a reference class Foo: num = 0 def fun1 (aFoo): aFoo.num = 1 print aFoo.num def fun2 (aFoo): temp = Foo () temp.num = 2 aFoo = temp print aFoo.num # MAIN aFoo = Foo () fun1 (aFoo) print aFoo.num fun2 (aFoo) print aFoo.num
  • #9: Notes: Again defining a class (attributes outside of a method) this way isn’t standard to Python but puts them into a familiar style next semester for Java/233.
  • #10: [csc classes 9 ]> python3 client.py James Tam (123)456-7890 [email protected] 0
  • #11: Talk about computer games where you want to track information different entities e.g., monsters, objects, walls etc. The information tracked with one game may differ from another game, you can do this by defining a different type of variable for each game that tracks different information.
  • #16: U:\www\231\examples\classes_objects>python person.py My name is... I have no name :( My name is... Big Smiley :D
  • #18: Draw memory maps: Main function: containing the references and objects bart and lisa sayName method: the self reference points to first the lisa object in main and then the bart object
  • #20: The underscore is used by Python for methods with special meaning (page 475 of the Monty Python book: “The practice of computing using Python” __init__ constructor __str__ returns a string representation of an object
  • #22: [csc classes 21 ]> python3 init_method1.py Finder Wyvernspur
  • #28: Smiley. name = "I have no name"): Jt.name = "James"
  • #29: U:\www\231\examples\classes_objects>python init_method2.py My name is... I have no name <= set to default parameter’s value My name is... James <= set to whatever is actually passed in during the call
  • #30: Import from Python.org http://docs.python.org/tutorial/modules.html Import syntax from fun import fun
  • #32: [csc modules1 26 ]> python3 main.py I'm fun1! I'm fun2! I'm fun3! Because fun1 and fun2 in includes file and function name they can be called using the function name only Fun3 imports only the file name so the call must include file and function name
  • #34: James Tam 11/11/2011 Check case: Does the case in the import have to match the case of the file (YES) [csc modules2 31 ]> python3 Driver.py Hello! Hallo! Sup?! Guten tag/morgen/aben! Buenos! Wei! Konichiwa! Shalom! Bonjour! Salaam alikum! Kamostaka?