SlideShare a Scribd company logo
Python
Classes 1
Edited
by
:
Nouf
almunyif
1
Introduction to Classes
and Object Oriented
programming
Edited
by
:
Nouf
almunyif
2
Two methods of programming:
• Procedural
• Object-oriented
Edited
by
:
Nouf
almunyif
3
Procedural Programming
•Procedural programming: writing programs made of
functions that perform specific tasks
 Procedures typically operate on data items that are
separate from the procedures
 Data items commonly passed from one procedure to
another
 Focus: to create procedures that operate on the
program’s data
Edited
by
:
Nouf
almunyif
4
Object-Oriented Programming
•An object represents an entity in the real world that can be
distinctly identified.
• You can look around you now and see many examples of real-world
objects: your cat, your television set, your bicycle, a student, a desk,
a circle, a button and point
• These real-world objects share two characteristics: they all have
state and they all have behavior
• For example, dogs have state (name, color, breed, hungry) and dogs
have behavior (barking, fetching).
Edited
by
:
Nouf
almunyif
5
Object-Oriented Programming
•Object-oriented programming: focused on creating
objects
• Object: Software objects are modeled after real-world objects in that
they, too, have state and behavior.
• A software object maintains its state in variables and implements its
behavior with methods.
• WHY USE OOP AND CLASSES OF OBJECTS ?
 mimic real life
 group different objects part of the same type
Edited
by
:
Nouf
almunyif
6
Encapsulation in Python
• Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP). It describes the idea of wrapping data and the
methods that work on data within one unit. This puts restrictions on
accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an
object’s variable can only be changed by an object’s method. Those
types of variables are known as private variable.
A class is an example of encapsulation as it encapsulates all the data
that is member functions, variables, etc.
Edited
by
:
Nouf
almunyif
7
Object-Oriented Programming
(cont’d.)
Edited
by
:
Nouf
almunyif
8
• Python is a completely object-oriented language. You have
been working with classes and objects right from the
beginning of these course .
Every element in a Python program is an object of a class.
A number, string, list, etc., used in a program is an object of
a corresponding built-in class. You can retrieve the class
name of variables or objects using the type() method
Edited
by
:
Nouf
almunyif
9
Classes
Edited
by
:
Nouf
almunyif
10
Classes
•Class: code that specifies the data attributes and methods
of a particular type of object
 Similar to a blueprint of a house or a cookie cutter
•Instance: an object created from a class
 Similar to a specific house built according to the
blueprint or a specific cookie
 There can be many instances of one class
Edited
by
:
Nouf
almunyif
11
Classes (cont’d.)
Edited
by
:
Nouf
almunyif
12
Classes (cont’d.)
Edited
by
:
Nouf
almunyif
13
Implementing the Class Vs Using the Class
Edited
by
:
Nouf
almunyif
14
Class Definitions
•Class definition: set of statements that define a
class’s methods and data attributes
 Format: begin with class Class_name:
•Class names often start with uppercase letter
Class Name: Circle
Data Fields:
radius is _______
Methods:
getArea
Circle Object 1
Data Fields:
radius is 10
Circle Object 2
Data Fields:
radius is 25
Circle Object 3
Data Fields:
radius is 125
A class template
Three objects of
the Circle class
Edited
by
:
Nouf
almunyif
15
Class Definitions
A Python class uses variables to store data fields and defines
methods to perform actions. Additionally, a class provides a special
type method, known as initializer, which is invoked to create a new
object. An initializer can perform any action, but initializer is
designed to perform initializing actions, such as creating the data
fields of objects.
 Format: def __init__ (self):
Usually the first method in a class definition
 Method definition like any other python function definition
• self parameter: required in every method in the class – references the
specific object that the method is working on
It does not have to be named self , you can call it whatever you like,
but it has to be the first parameter of any function in the class:
Edited
by
:
Nouf
almunyif
16
Examples
a class attribute defined
inside a class. Its value will
remain the same for all the
objects unless modified
explicitly
Edited
by
:
Nouf
almunyif
17
•To create a new instance of a class call the initializer method
Format: My_instance = Class_Name()
Edited
by
:
Nouf
almunyif
18
class attribute
• The following example demonstrates the use of class attribute
Edited
by
:
Nouf
almunyif
19
Instances
Edited
by
:
Nouf
almunyif
20
Working With Instances
•Instance attribute: belongs to a specific instance
of a class
 Created when a method uses the self parameter to
create an attribute
•If many instances of a class are created, each
would have its own set of attributes
Edited
by
:
Nouf
almunyif
21
class attribute
• The following example demonstrates the use of class attribute
Edited
by
:
Nouf
almunyif
22
Class Abstraction and Encapsulation
Class abstraction means to separate class
implementation from the use of the class. The creator of
the class provides a description of the class and let the
user know how the class can be used. The user of the
class does not need to know how the class is
implemented. The detail of implementation is
encapsulated and hidden from the user.
Edited
by
:
Nouf
almunyif
23
• To call any of the class methods using the created instance, use
dot notation
 Format: My_instance.method()
Edited
by
:
Nouf
almunyif
24
python __init__
• The function init(self) builds your object.
Its not just variables you can set here, you
can call class methods too. Everything you
need to initialize the object(s).
• It is known as a constructor in object oriented concepts.
Edited
by
:
Nouf
almunyif
25
Object-Oriented Programming
•Data hiding: object’s data attributes are hidden from code outside
the object
 Access restricted to the object’s methods
•Protects from accidental corruption
•Outside code does not need to know internal structure of the
object
•Public methods: allow external code to manipulate the object
•Private methods: used for object’s inner workings
•Object reusability: the same object can be used in different
programs
Edited
by
:
Nouf
almunyif
26
Protected members
• Protected members (in C++ and JAVA) are those members of the class that
cannot be accessed outside the class but can be accessed from within the
class and its subclasses. To accomplish this in Python, just follow the
convention by prefixing the name of the member by a single underscore “_”.
• Single Leading Underscore: _var
it has a meaning by convention only(This isn’t enforced by Python), is meant as
a hint to another programmer that a variable or method starting with a single
underscore is intended for internal use
Edited
by
:
Nouf
almunyif
27
•An object’s data attributes should be private which means they cannot
be accessed except inside a class
in Python, there is no existence of Private instance variables . However,
to define a private member prefix the member name with double
underscore “__”.
Private members
Edited
by
:
Nouf
almunyif
28
Accessor and Mutator Methods
•Typically, all of a class’s data attributes are private and
provide methods to access and change them
•Accessor methods: return a value from a class’s attribute
without changing it
 Safe way for code outside the class to retrieve the value
of attributes
•Mutator methods: store or change the value of a data
attribute
Edited
by
:
Nouf
almunyif
29
Getter and Setter in Python
• Class variables need not be set directly:
they can be set using class methods. This is
the object orientated way and helps you
avoid mistakes.
Edited
by
:
Nouf
almunyif
30
How can you set a default values to the instance
attributes, So, if the values are not provided when
creating an object, the values will be assigned latter?
Storing Classes in Modules
•Classes can be stored in modules
 Filename for module must end in .py
 Module can be imported to programs that use the class
Edited
by
:
Nouf
almunyif
31
Calling Methods
• A client can call the methods of an object in
two ways:
1) object.method(parameters)
2) Class.method(object, parameters)
Edited
by
:
Nouf
almunyif
32
The __str__ method
•Object’s state: the values of the object’s attribute at
a given moment
•__str__ method: displays the object’s state,
 It’s Automatically called when the object is passed
as an argument to the print function
Edited
by
:
Nouf
almunyif
33
returns a string that describes the pointer of the object
If we don’t implement __str__() function for a class, then
built-in object implementation is used that actually calls
__repr__() function.
The __str__ method
Edited
by
:
Nouf
almunyif
34
The custom __str__ method should be defined in a way that is easy to read and
returns all the members of the class as a string .
another way to write __str__ function
def __str__(self):
return "{} any text you want {} any text you want {}".format(self.attr1, self.attr2, self.attr3)
The __repr__ method
• The __repr__ method returns a string that describes the pointer
of the object by default (if the programmer does not define it).
Edited
by
:
Nouf
almunyif
35
The __repr__ method
Edited
by
:
Nouf
almunyif
36
__str __ Vs. __repr__
Edited
by
:
Nouf
almunyif
37
If both the functions return strings, which is supposed to be the
object representation, what’s the difference?
Well, the __str__ function is supposed to return a human-
readable format, which is good for logging or to display some
information about the object. Whereas, the __repr__ function is
supposed to return an “official” string representation of the
object, which can be used to construct the object again.
Examples
Edited
by
:
Nouf
almunyif
38
Edited
by
:
Nouf
almunyif
39
Edited
by
:
Nouf
almunyif
40
Passing Objects as an
Arguments
Edited
by
:
Nouf
almunyif
41
Passing Objects as Arguments
•Methods and functions often need to accept
objects as arguments
•When you pass an object as an argument, you are
actually passing a reference to the object
 The receiving method or function has access to the
actual object
•Methods of the object can be called within the receiving function
or method, and data attributes may be changed using mutator
methods
Edited
by
:
Nouf
almunyif
42
example
Edited
by
:
Nouf
almunyif
43
Techniques for Designing Classes
•UML diagram: standard diagrams for graphically
depicting object-oriented systems
 Stands for Unified Modeling Language
•General layout: box divided into three sections:
 Top section: name of the class
 Middle section: list of data attributes
 Bottom section: list of class methods
Edited
by
:
Nouf
almunyif
44
Edited
by
:
Nouf
almunyif
45
Example : implement the following
Loan
-annualInterestRate: float
-numberOfYears: int
-loanAmount: float
-borrower: str
Loan(annualInterestRate: float,
numberOfYear: int, loanAmount:
float, borrower: str)
The annual interest rate of the loan (default: 2.5).
The number of years for the loan (default: 1)
The loan amount (default: 1000).
The borrower of this loan.
Constructs a Loan object with the specified annual
interest rate, number of years, loan amount, and
borrower.
The get methods for these data fields are
provided in the class, but omitted in the
UML diagram for brevity.
The – sign denotes a private data field.
Edited
by
:
Nouf
almunyif
46
More on classes
Edited
by
:
Nouf
almunyif
47
Deleting object
• How to Delete Python Object ?
• To delete an object in Python, we use the ‘del’ keyword. A when we
try to refer to a deleted object, it raises NameError.
Edited
by
:
Nouf
almunyif
48
How can you delete object properties?
Does it delete from that object only
or from all of the objects from same
class?
The pass Statement
class definitions cannot be empty, but if you for some
reason have a class definition with no content, put in
the pass statement to avoid getting an error.
Example
class Person:
pass
Edited
by
:
Nouf
almunyif
49
Single Trailing Unders : var_
Sometimes the most fitting name for a variable is already taken
by a keyword. Therefore names like class or def cannot be used
as variable names in Python. In this case you can append a
single underscore to break the naming conflictcore
The Meaning of Underscores in Python
Python None Keyword
The None keyword is used to define a null value, or no value at all.
None is not the same as 0, False, or an empty string.
None is a data type of its own (NoneType) and only None can be None.
Edited
by
:
Nouf
almunyif
50
built-in functions
Edited
by
:
Nouf
almunyif
51
built-in Getter and Setter in Python
• The setattr() function sets the value of the specified
attribute of the specified object.
• Syntax : setattr(object, attribute, value)
Edited
by
:
Nouf
almunyif
52
built-in Getter and Setter in Python
• The setattr() function can be used to create data attributes of a
class in run-time
Edited
by
:
Nouf
almunyif
53
built-in Getter and Setter in Python
• The getattr() function returns the value of the specified attribute
from the specified object.
• Syntax : getattr(object, attribute, default)
default Optional :
The value to return if the attribute does not exist
Edited
by
:
Nouf
almunyif
54
built-in hasattr() in Python
• hasattr() : returns True if the specified object has the
specified attribute, otherwise False.
• Syntax : hasattr(object, attribute)
Edited
by
:
Nouf
almunyif
55
built-in isinstance() in Python
• isinstance() : takes two arguments, an object and a class.
It checks if the object in the first argument is an
instance of the class in the second argument and returns
either True or False
 Format: isinstance(object, class)
Edited
by
:
Nouf
almunyif
56
References:
• Tony Gaddis - Starting Out with Python, Global Edition (2018, Pearson
Education)
• https://www.w3schools.com/python/python_file_open.asp
• https://www.geeksforgeeks.org/encapsulation-in-python/
• https://www.educative.io/edpresso/what-is-the-str-method-in-python
• https://www.journaldev.com/22460/python-str-repr-functions
• https://www.w3schools.com/python/python_ref_functions.asp
• https://data-flair.training/blogs/python-object/
Edited
by
:
Nouf
almunyif
57

More Related Content

PPTX
classes and objects of python object oriented
PPTX
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
PPTX
Python_Unit_2 OOPS.pptx
PPTX
software construction and development week 3 Python lists, tuples, dictionari...
PPTX
Python OOPs
PPTX
Lec-21-Classes and Object Orientation.pptx
PPT
07slide.ppt
classes and objects of python object oriented
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
Python_Unit_2 OOPS.pptx
software construction and development week 3 Python lists, tuples, dictionari...
Python OOPs
Lec-21-Classes and Object Orientation.pptx
07slide.ppt

Similar to مقدمة بايثون .pptx (20)

PPTX
Object Oriented Programming.pptx
PDF
Python Programming - Object-Oriented
PDF
OOP in Python, a beginners guide..........
PPTX
Basics of Object Oriented Programming in Python
PPTX
Python-Classes.pptx
PPTX
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
PDF
Unit 3-Classes ,Objects and Inheritance.pdf
PPTX
Object Oriented Programming in Python
PPTX
OOPS 46 slide Python concepts .pptx
PPTX
Unit – V Object Oriented Programming in Python.pptx
PPTX
slides11-objects_and_classes in python.pptx
PPTX
oopinpyhtonnew-140722060241-phpapp01.pptx
PPTX
object oriented porgramming using Java programming
PPTX
Object Oriented Programming Class and Objects
PPTX
IPP-M5-C1-Classes _ Objects python -S2.pptx
PPTX
Module-5-Classes and Objects for Python Programming.pptx
PPTX
python.pptx
PPTX
Python 2. classes- cruciql for students objects1.pptx
PPTX
basic concepts of object oriented in python
PPTX
Regex,functions, inheritance,class, attribute,overloding
Object Oriented Programming.pptx
Python Programming - Object-Oriented
OOP in Python, a beginners guide..........
Basics of Object Oriented Programming in Python
Python-Classes.pptx
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
Unit 3-Classes ,Objects and Inheritance.pdf
Object Oriented Programming in Python
OOPS 46 slide Python concepts .pptx
Unit – V Object Oriented Programming in Python.pptx
slides11-objects_and_classes in python.pptx
oopinpyhtonnew-140722060241-phpapp01.pptx
object oriented porgramming using Java programming
Object Oriented Programming Class and Objects
IPP-M5-C1-Classes _ Objects python -S2.pptx
Module-5-Classes and Objects for Python Programming.pptx
python.pptx
Python 2. classes- cruciql for students objects1.pptx
basic concepts of object oriented in python
Regex,functions, inheritance,class, attribute,overloding
Ad

Recently uploaded (20)

PPTX
master seminar digital applications in india
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Pre independence Education in Inndia.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Cell Types and Its function , kingdom of life
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
master seminar digital applications in india
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Pre independence Education in Inndia.pdf
Anesthesia in Laparoscopic Surgery in India
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Abdominal Access Techniques with Prof. Dr. R K Mishra
O7-L3 Supply Chain Operations - ICLT Program
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Cell Types and Its function , kingdom of life
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPH.pptx obstetrics and gynecology in nursing
Ad

مقدمة بايثون .pptx

  • 2. Introduction to Classes and Object Oriented programming Edited by : Nouf almunyif 2
  • 3. Two methods of programming: • Procedural • Object-oriented Edited by : Nouf almunyif 3
  • 4. Procedural Programming •Procedural programming: writing programs made of functions that perform specific tasks  Procedures typically operate on data items that are separate from the procedures  Data items commonly passed from one procedure to another  Focus: to create procedures that operate on the program’s data Edited by : Nouf almunyif 4
  • 5. Object-Oriented Programming •An object represents an entity in the real world that can be distinctly identified. • You can look around you now and see many examples of real-world objects: your cat, your television set, your bicycle, a student, a desk, a circle, a button and point • These real-world objects share two characteristics: they all have state and they all have behavior • For example, dogs have state (name, color, breed, hungry) and dogs have behavior (barking, fetching). Edited by : Nouf almunyif 5
  • 6. Object-Oriented Programming •Object-oriented programming: focused on creating objects • Object: Software objects are modeled after real-world objects in that they, too, have state and behavior. • A software object maintains its state in variables and implements its behavior with methods. • WHY USE OOP AND CLASSES OF OBJECTS ?  mimic real life  group different objects part of the same type Edited by : Nouf almunyif 6
  • 7. Encapsulation in Python • Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes the idea of wrapping data and the methods that work on data within one unit. This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data. To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variable. A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc. Edited by : Nouf almunyif 7
  • 9. • Python is a completely object-oriented language. You have been working with classes and objects right from the beginning of these course . Every element in a Python program is an object of a class. A number, string, list, etc., used in a program is an object of a corresponding built-in class. You can retrieve the class name of variables or objects using the type() method Edited by : Nouf almunyif 9
  • 11. Classes •Class: code that specifies the data attributes and methods of a particular type of object  Similar to a blueprint of a house or a cookie cutter •Instance: an object created from a class  Similar to a specific house built according to the blueprint or a specific cookie  There can be many instances of one class Edited by : Nouf almunyif 11
  • 14. Implementing the Class Vs Using the Class Edited by : Nouf almunyif 14
  • 15. Class Definitions •Class definition: set of statements that define a class’s methods and data attributes  Format: begin with class Class_name: •Class names often start with uppercase letter Class Name: Circle Data Fields: radius is _______ Methods: getArea Circle Object 1 Data Fields: radius is 10 Circle Object 2 Data Fields: radius is 25 Circle Object 3 Data Fields: radius is 125 A class template Three objects of the Circle class Edited by : Nouf almunyif 15
  • 16. Class Definitions A Python class uses variables to store data fields and defines methods to perform actions. Additionally, a class provides a special type method, known as initializer, which is invoked to create a new object. An initializer can perform any action, but initializer is designed to perform initializing actions, such as creating the data fields of objects.  Format: def __init__ (self): Usually the first method in a class definition  Method definition like any other python function definition • self parameter: required in every method in the class – references the specific object that the method is working on It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class: Edited by : Nouf almunyif 16
  • 17. Examples a class attribute defined inside a class. Its value will remain the same for all the objects unless modified explicitly Edited by : Nouf almunyif 17
  • 18. •To create a new instance of a class call the initializer method Format: My_instance = Class_Name() Edited by : Nouf almunyif 18
  • 19. class attribute • The following example demonstrates the use of class attribute Edited by : Nouf almunyif 19
  • 21. Working With Instances •Instance attribute: belongs to a specific instance of a class  Created when a method uses the self parameter to create an attribute •If many instances of a class are created, each would have its own set of attributes Edited by : Nouf almunyif 21
  • 22. class attribute • The following example demonstrates the use of class attribute Edited by : Nouf almunyif 22
  • 23. Class Abstraction and Encapsulation Class abstraction means to separate class implementation from the use of the class. The creator of the class provides a description of the class and let the user know how the class can be used. The user of the class does not need to know how the class is implemented. The detail of implementation is encapsulated and hidden from the user. Edited by : Nouf almunyif 23
  • 24. • To call any of the class methods using the created instance, use dot notation  Format: My_instance.method() Edited by : Nouf almunyif 24
  • 25. python __init__ • The function init(self) builds your object. Its not just variables you can set here, you can call class methods too. Everything you need to initialize the object(s). • It is known as a constructor in object oriented concepts. Edited by : Nouf almunyif 25
  • 26. Object-Oriented Programming •Data hiding: object’s data attributes are hidden from code outside the object  Access restricted to the object’s methods •Protects from accidental corruption •Outside code does not need to know internal structure of the object •Public methods: allow external code to manipulate the object •Private methods: used for object’s inner workings •Object reusability: the same object can be used in different programs Edited by : Nouf almunyif 26
  • 27. Protected members • Protected members (in C++ and JAVA) are those members of the class that cannot be accessed outside the class but can be accessed from within the class and its subclasses. To accomplish this in Python, just follow the convention by prefixing the name of the member by a single underscore “_”. • Single Leading Underscore: _var it has a meaning by convention only(This isn’t enforced by Python), is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use Edited by : Nouf almunyif 27
  • 28. •An object’s data attributes should be private which means they cannot be accessed except inside a class in Python, there is no existence of Private instance variables . However, to define a private member prefix the member name with double underscore “__”. Private members Edited by : Nouf almunyif 28
  • 29. Accessor and Mutator Methods •Typically, all of a class’s data attributes are private and provide methods to access and change them •Accessor methods: return a value from a class’s attribute without changing it  Safe way for code outside the class to retrieve the value of attributes •Mutator methods: store or change the value of a data attribute Edited by : Nouf almunyif 29
  • 30. Getter and Setter in Python • Class variables need not be set directly: they can be set using class methods. This is the object orientated way and helps you avoid mistakes. Edited by : Nouf almunyif 30 How can you set a default values to the instance attributes, So, if the values are not provided when creating an object, the values will be assigned latter?
  • 31. Storing Classes in Modules •Classes can be stored in modules  Filename for module must end in .py  Module can be imported to programs that use the class Edited by : Nouf almunyif 31
  • 32. Calling Methods • A client can call the methods of an object in two ways: 1) object.method(parameters) 2) Class.method(object, parameters) Edited by : Nouf almunyif 32
  • 33. The __str__ method •Object’s state: the values of the object’s attribute at a given moment •__str__ method: displays the object’s state,  It’s Automatically called when the object is passed as an argument to the print function Edited by : Nouf almunyif 33 returns a string that describes the pointer of the object If we don’t implement __str__() function for a class, then built-in object implementation is used that actually calls __repr__() function.
  • 34. The __str__ method Edited by : Nouf almunyif 34 The custom __str__ method should be defined in a way that is easy to read and returns all the members of the class as a string . another way to write __str__ function def __str__(self): return "{} any text you want {} any text you want {}".format(self.attr1, self.attr2, self.attr3)
  • 35. The __repr__ method • The __repr__ method returns a string that describes the pointer of the object by default (if the programmer does not define it). Edited by : Nouf almunyif 35
  • 37. __str __ Vs. __repr__ Edited by : Nouf almunyif 37 If both the functions return strings, which is supposed to be the object representation, what’s the difference? Well, the __str__ function is supposed to return a human- readable format, which is good for logging or to display some information about the object. Whereas, the __repr__ function is supposed to return an “official” string representation of the object, which can be used to construct the object again.
  • 41. Passing Objects as an Arguments Edited by : Nouf almunyif 41
  • 42. Passing Objects as Arguments •Methods and functions often need to accept objects as arguments •When you pass an object as an argument, you are actually passing a reference to the object  The receiving method or function has access to the actual object •Methods of the object can be called within the receiving function or method, and data attributes may be changed using mutator methods Edited by : Nouf almunyif 42
  • 44. Techniques for Designing Classes •UML diagram: standard diagrams for graphically depicting object-oriented systems  Stands for Unified Modeling Language •General layout: box divided into three sections:  Top section: name of the class  Middle section: list of data attributes  Bottom section: list of class methods Edited by : Nouf almunyif 44
  • 46. Example : implement the following Loan -annualInterestRate: float -numberOfYears: int -loanAmount: float -borrower: str Loan(annualInterestRate: float, numberOfYear: int, loanAmount: float, borrower: str) The annual interest rate of the loan (default: 2.5). The number of years for the loan (default: 1) The loan amount (default: 1000). The borrower of this loan. Constructs a Loan object with the specified annual interest rate, number of years, loan amount, and borrower. The get methods for these data fields are provided in the class, but omitted in the UML diagram for brevity. The – sign denotes a private data field. Edited by : Nouf almunyif 46
  • 48. Deleting object • How to Delete Python Object ? • To delete an object in Python, we use the ‘del’ keyword. A when we try to refer to a deleted object, it raises NameError. Edited by : Nouf almunyif 48 How can you delete object properties? Does it delete from that object only or from all of the objects from same class?
  • 49. The pass Statement class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error. Example class Person: pass Edited by : Nouf almunyif 49 Single Trailing Unders : var_ Sometimes the most fitting name for a variable is already taken by a keyword. Therefore names like class or def cannot be used as variable names in Python. In this case you can append a single underscore to break the naming conflictcore The Meaning of Underscores in Python
  • 50. Python None Keyword The None keyword is used to define a null value, or no value at all. None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None. Edited by : Nouf almunyif 50
  • 52. built-in Getter and Setter in Python • The setattr() function sets the value of the specified attribute of the specified object. • Syntax : setattr(object, attribute, value) Edited by : Nouf almunyif 52
  • 53. built-in Getter and Setter in Python • The setattr() function can be used to create data attributes of a class in run-time Edited by : Nouf almunyif 53
  • 54. built-in Getter and Setter in Python • The getattr() function returns the value of the specified attribute from the specified object. • Syntax : getattr(object, attribute, default) default Optional : The value to return if the attribute does not exist Edited by : Nouf almunyif 54
  • 55. built-in hasattr() in Python • hasattr() : returns True if the specified object has the specified attribute, otherwise False. • Syntax : hasattr(object, attribute) Edited by : Nouf almunyif 55
  • 56. built-in isinstance() in Python • isinstance() : takes two arguments, an object and a class. It checks if the object in the first argument is an instance of the class in the second argument and returns either True or False  Format: isinstance(object, class) Edited by : Nouf almunyif 56
  • 57. References: • Tony Gaddis - Starting Out with Python, Global Edition (2018, Pearson Education) • https://www.w3schools.com/python/python_file_open.asp • https://www.geeksforgeeks.org/encapsulation-in-python/ • https://www.educative.io/edpresso/what-is-the-str-method-in-python • https://www.journaldev.com/22460/python-str-repr-functions • https://www.w3schools.com/python/python_ref_functions.asp • https://data-flair.training/blogs/python-object/ Edited by : Nouf almunyif 57