Object Oriented Programming vs. Procedural Programming – Objects, Classes, and Methods
In object-oriented programming (OOP), all data (including all data types and functions) are objects. Objects are entities that contain both data and functionality together. The operations (methods) that can be done on a particular data type are bound to that object. This means that the types of data and the operations on them are connected in the language.
Procedural Programming
So far, you have learned about various data types such as integer, float, string, list, and dict (dictionary). You have also learned about various operators such as add, subtract, multiply, divide, etc. We did various example programs using these data types and various operators. So far, all the Python programming examples on this website use procedural programming techniques and syntax.
How Do We Provide Modularity In Procedural Programs
You saw from examples in previous pages of this website that we provide modularity by using functions by grouping commonly used groups of statements in procedural programming. And we used dictionary data type to group related sets of data together. In procedural programming, functions operate on data (like integers, strings, lists, dictionaries, etc.) These techniques work very well to make the program short, concise, and modular. Modular programs provide maintainability and readability.
Why Do We Need Object Oriented Programming
As the programs become more complex that include hundreds of variables and hundreds of functions, the procedural programming techniques result in programs that are difficult to maintain and debug.
In procedural programming, the data and the operators are not bound to each other in the language. They are separate entities.
In object-oriented programming (OOP), both data and functionality are bound together.
In OOP, all data (that includes all data types and even functions) are objects.
So, what are objects?
Objects are entities that contain both data and functionality together. The operations that can be done on a particular data type are bound to that object, meaning that types of data and the operations on them are connected in the language. These operations are called object’s methods.
Advantages of Object Oriented Programming
The advantages of Object Oriented Programming are that:
- OOP results in higher-quality software;
- The objects can be reused in other parts of the program, in other programs, or even in other projects.
- The OOP programs are modular. Therefore, they are easier to maintain and easier to debug.
In summary, Object-oriented programming is a better way to write programs.
More reading on Object Oriented Programming is at this link.
Roadmap Of Object Oriented Programming Chapter
We will explain the basics of object-oriented programming by introducing the concept of classes, objects, and methods.
To explain the object-oriented programming paradigm, we will use the solar system example used in earlier chapters.
In the earlier chapters, we used solar system facts to write programs using procedural programming. In this chapter, we will write similar programs using the OOP techniques to illustrate the differences.
Let’s first review the theory of class, object, and methods before we get into OOP software programming.
What Are Classes In Object Oriented Programming
Classes are a way of combining information and behavior.
On the Python Data Types page, we learned that the data type dictionary (dict) is used to group related data together (key:value).
In Python Functions 1 and Python Functions 2 page, we learned that functions are a way to group together a commonly used set of statements to provide certain behavior (functionality).
The introduction of this chapter stated that it is useful to have the means to bind data and functionality together, especially when the programs become large. In object-oriented programming, classes provide a means of binding data and functionality together. This functionality is called methods of the data type.
Example to Explain What Is A “class” and an “object””
Class is an abstract concept. Perhaps, an example will help clarify what class in object-oriented programming means. The term ‘dog’ is a generic term for the animal dog, whereas a bulldog, golden retriever, or poodle is a variety (breed) of dog. In object-oriented programming languages like Python, the term ‘dog’ is called a class, and a bulldog, golden retriever, or poodle is called an object in the class ‘dog’. The bulldog, a golden retriever, and a poodle are referred to as an instance of class ‘dog’ and are called objects.
Another Example To Explain “class” And “object” Concept
Let us look at another example to help explain the concept of class and object. We will use our solar system as an example.
In OOP, the word “planet” is a class. The words Mercury, Venus, Earth, and Mars are instances of the generic term “planet”. The planets Mercury, Venus, Earth, Mars, etc. are objects in the “planet” class.
When we write OOP programs, one of the first things we do is to create an object of a class. When we create an object of a class data type, we call it an instance of a class. Creating an instance (object) of a class is called instantiation.
How do we create a class?
A class is created by typing the keyword class followed by the class name (“planet” in the example below), followed by open and close parentheses, and a colon (:). The statement is ended with the ENTER key.
When you press the ENTER key, Python automatically indents the next line by tab space. Do not backspace the indent.
The body of the class starts at this indent and contains the body statements. The body of the class code has associated with it a few class attributes and a few class methods.
Attributes are variables that belong to the class and are accessed by creating an object of the class. Attributes and methods are explained in the next section.
The following example code creates a class named “planet”.
PROGRAM EXAMPLE: HOW TO CREATE A CLASS
Program Name: Python_OOP_define_class
Python 3.11.3 (tags/v3.11.3:f3909b8, Apr 4 2023, 23:49:59) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> class planet():
... # Define a clas named planet
... #
...
The line class planet(): tells Python that a class is going to be created. The keyword class is followed by the name of the class. The rules for naming the class are the same as that for naming a variable.
Note the parenthesis after the class name is followed by the symbol colon (:).
Objects
As indicated in the class paragraph above, an object is an instance of a class data type. In Python, all types of data are objects. All Python entities are instances of some class.
To create an object, we first need to create a class. Creating a new class enables us to create new instances of that class type. These instances are called objects. Creating an object of a class is called instantiation, and the object we created is called an instance of that class.
Class Instance Attributes
The class has associated with it a few class attributes and a few class methods.
An object is an instance of the class; it has a copy of each of the class’s variables (attributes), and it can do any action that is defined for the class
The program example below creates a class “planet” that has associated with it two class attributes called “DistanceN” and “DistanceU”.
Class instances (objects) have methods associated with them in addition to attributes.
The methods are similar to functions. We will discuss methods in a later section.
Object Summary
In summary, an object consists of:
- Object: An object is a particular instance of a class. An object has a certain set of values for all of the attributes (variables) in the class. The object has a unique name. In the program example below, “planetN” is an object in the class “planet”. You can use any name except the keywords and reserved words.
- Attributes: are properties of the object. An attribute is just a variable that is part of a class. In the code below, “distanceN” and “distanceU” are attributes of the class “planet”.
- Function (methods): are the behavior or functionality. The behavior is defined within a class. It provides the functionality that operates on the objects. The behavior are referred to as methods, which are just functions that are defined for the class. We will discuss methods in detail in a later section.
When an object of a class is instantiated, all instances get the attributes and the behavior (methods) of the class. However, the value of the attributes is unique to the individual object. In the program example below, object “planetN” has the attribute “distanceN”, and object “planetU” has the attribute “distanceU”. An object is a single instance of the Rocket class; it has a copy of each of the class’s variables, and it can do any action that is defined for the class
How to Instantiate An Object Of A Class
To create an object of a class:
- First create a variable name such as “planetN” in the program below.
- Then, set that variable name equal to the name of the class with an empty open and close parentheses.
- Python creates an object from the class with the name you specify in step 1) above
The program example below shows how to create instantiations of a class. The code creates two instances of the class “planet” and names them “planetN” and “planetU”. The class “planet” has associated with it two class attributes called “DistanceN” and “DistanceU”.
PROGRAM EXAMPLE: INSTANTIATE AN OBJECT OF A CLASS
Program Name: Python_OOP_instantiate_object.py
1 class planet():
2 # Define a clas named planet
3 #
4 def __init__(self):
5 self.distanceN = 2970
6 # parameter distanceN is the distance of planet Neptune from the Sun.
7 self.distanceU = 1786
8 # parameter distanceU is the distance of planet Uranus from the Sun.
9
10 # Instantiate two objects of class planet and name them "planetN" and "planetU".
11 planetN = planet()
12 planetU = planet()
The class stores two pieces of information so far: “distanceN” and “distanceU”. But the program can’t do anything yet. We have to define the behavior of the class first. This will be done in the next few sections.
Explanation of the Program
Line 4: def __init__(self):
The first thing you do when we define a class is to use the __init__()
method. The __init__()
method sets the values of parameters that need to be defined when an object of the class is created.
Notice the def
__init__()
statement in the program above. The self in the parenthesis is a syntax that allows you to access a variable from anywhere else in the class. Just keep in mind that all OOP programs must havethe def
__init__()
statement with self as the first parameter.
The function names that start and end with two underscores are special built-in functions for Python’s internal uses. The def
__init__()
method is one of these special functions. Python calls the def
__init__()
method when you instantiate an object of a class. The __init__()
method sets all attributes to their proper values when an object is created from the class.
Line 5: self.distanceN = 2970
Line 7: self.distanceU = 1786
Lines 5 and line 7: The __init__()
method initializes the attribute “distanceN” to a value 2970 and the attribute “distanceU” to the value 1786.
How to Create Object’s Methods (Behavior)
Lines 13 – 15 in tThe program below define the behavior of the class “planet” by creating the method called “movePlanets”.
Note that each method must have one argument by default (self). The argument self is a reference to the particular object that is calling the method. This self argument gives access to the calling object’s attributes.
In the program below, the self argument is used to access a “planet” object’s attributes “distanceN” and “distanceU”
The “movePlanets” method increases the distance of planetN by incrementing the variable “distanceN” by 200 “movePlanets” method is called by the object “planetN”.
Likewise, the “movePlanets” method increases the distance of planetU by incrementing the variable “distanceU” by 100 each time “movePlanets” method is called by the object planetU.
Lines 18 – 19 instantiate two objects “planetN” and “planetU” that are instances of the class “planet”.
PROGRAM EXAMPLE: OBJECT’S METHODS OF A CLASS
Program Name: python_OOP_object_method.py
1 class planet():
2 # Define a clas named planet
3 #
4 def __init__(self):
5 self.distanceN = 2970
6 # parameter distanceN is the distance of planet Neptune from the Sun.
7 self.distanceU = 1786
8 # parameter distanceU is the distance of planet Uranus from the Sun.
9
10
11
12 #Define a function to move the planets.
13 def movePlanets(self):
14 self.distanceN += 200
15 self.distanceU += 100
16
17 # Instantiate two objects of class planet and name them "planetN" and "planetU".
18 planetN = planet()
19 planetU = planet()
If you run this program, the program will not do anything yet. For the program to do someting interesting, we need to call the object’s methods. We do this next.
Methods
Let’s discuss what methods are. We described functions in Python Functions 1 and Python Functions 2 chapters. Functions are used in Procedural Programming.
In object-oriented programming, a method is a function as well. Just like functions, methods provide the functionality of an object. There are a certain group of operations that can be done on a particular object. These operations are called object’s methods. These methods are associated with the object, in other words, belong to the object. Just like other data types we have studied so far, an object is also a data type; it just happens to have methods associated with it. The operations on the objects are done by methods using the dot (.) operator as described below.
Program Example: Call Object’s Methods
######## Define Class, object instantiation, call object's methods. ########
2 class planet():
3 # Define a clas named planet
4 #
5 def __init__(self):
6 self.distanceN = 2970
7 # parameter distanceN is the distance of planet Neptune from the Sun.
8 self.distanceU = 1786
9 # parameter distanceU is the distance of planet Uranus from the Sun.
10
11 #Define a function to move the planets.
12 def movePlanets(self):
13 self.distanceN += 200
14 self.distanceU += 100
15
16 # Instantiate two objects of class planet and name them "planetN" and "planetU".
17 planetN = planet()
18 planetU = planet()
19
20 # Access the planetN object's variable distanceN using the dot notation.
21 print("Neptune distance from Sun =",planetN.distanceN)
22 # Access the planetU object's variable distanceU using the dot notation.
23 print("Uranus distance from Sun =",planetU.distanceU)
24 print()
25 # Move planet Neptune
26 # Access the planetN object's method using the dot notation.
27 planetN.movePlanets()
28 print("Neptune distance from Sun after move =",planetN.distanceN)
29 print()
30 # Move planet Uranus
31 # Access the planetU object's method using the dot notation.
32 planetU.movePlanets()
33 print("Uranus distance from Sun after move =",planetU.distanceU)
Detailed Explanation of the Program
The above program is the same as the program in the previous section except for the addition of lines 21 – 33.
Line 21: print(“Neptune distance from Sun =”,planetN.distanceN)
Line 21 accesses the “planetN” object’s variable “distanceN” using the dot operator (planetN.distanceN).
To access an object’s variables, the name of the object, followed by a dot (.), followed by name of the variable. In this case, the object name is “planetN” and the variable name is “distanceN”.
“planetN.distanceN”: The object “planetN” accesses the class variable “distanceN”. Similarly, the object “planetU” accesses the class variable “distanceU”.
Line 23: print(“Uranus distance from Sun =”,planetU.distanceU)
Similarly, Line 23 accesses the “planetU” object’s variable “distanceU” using the dot operator (planetU.distanceU), as explained above.
Line 27: planetN.movePlanets()
Line 32: planetU.movePlanets()
Lines 27 and line 32 call the “planet” class’s method “movePlanet().
Lines 27 access an object’s method by typing the object name, followed by a dot (.), followed by the method name. In this case, the object name is “planetN” and the method name is “movePlanets”.
Line 32 explanation for “planetU” is the same as in line 27.
The dot (.) operator (In More Detail)
In procedural programming, you learned about operators such as add (+), subtract (-), etc. in the Operators and Operands chapter. The dot(.) operator is the operator in object-oriented programming. The method (function) after the dot operates on the object to the left of the dot. To invoke the functionality (method), a dot (.) is placed between the object name and the method name. (Refer to the one line of code below.) Just as in procedural programming, the operators are +, -, /, etc., in OOP the dot between the object name and the method name is an operator. The dot is the operator and calls the method following the dot. The methods can access the class attributes using the dot (.) operator as in the example program below.
Dot Operator (.) Syntax
Following is the syntax of the object function call. This statement means that a function call is made to the method associated with the object.
>>> object.method()
In summary, an object is just another name for a value of a data type that has methods. The data type string
that we studied Python Data Type chapter is an object as well because the string
is data and its methods are upper()
, capitalize()
, count()
, etc. For
data type methods, see Program Example below.string
PROGRAM EXAMPLE: METHOD AND THE Dot(.) OPERATOR
Program Name: python_OOP_call_method.py
class planet(): #1)
def __init__(self): #2)
# CLASS ATTRIBUTES: Define class variables (attributes) #0)
self.distanceNep = 2970
self.distanceUra = 1786
# parameter "distanceNep" is the distance of planet Neptune from the Sun.
# parameter "distanceUra" is the distance of planet Uranus from the Sun.
# __init__ method initializes attribute "distanceNep" to 2970
# __init__ method initializes attribute "distanceUra" to i786
# CLASS METHODS
# Define a method to access class attribute ‘distanceNep’. #3)
def meth1(self):
print('Neptune is', self.distanceNep, 'million miles from Sun')
#
# Define a method to access class attribute ‘distanceUra’. #3)
def meth2(self):
print('Uranus is', self.distanceUra, 'million miles from Sun')
# Instantiate a ‘planet’ class object ‘neptune’. #4)
neptune = planet()
#
# Instantiate a ‘planet’ class object ‘uranus’. #4)
uranus = planet()
# call method ‘meth1’ to access class attribute ‘distanceNep’ #5)
neptune.meth1() #3)
#
# call method ‘meth2’ to access class attribute ‘distanceUra’ #6)
uranus.meth2() #4)
The following is the program’s output.
======== RESTART: C:/Users/Your name/Python_scripts/python_OOP_call_method.py =======
Neptune is 2970 million miles from Sun
Uranus is 1786 million miles from Sun
Method and Dot Operator Program Explanation
class planet():
In Llne 1), we create a class “planet”.
line 2): def init(self):
In this line of code, we have the initializer method (__init__)
followed by two class attributes (“distanceNep” and “distanceUra”). Note the use of the “self” parameter. The __init__
method can have several parameters, but the “self” parameter is required and must be the first one.
In the __init__
method, we initialized the “distanceNep” and “distanceUra” attributes to 2970 and 1786 respectively. Later on, we will use the print statement to print these attributes to see if we get the values we initialized to.
Line 3): def meth1(self):
and def meth2(self)
In step 3), we define two methods, “meth1” and “meth2”. These methods contain the functionality that will operate on the object to the left of the dot.
Note that the class methods “meth1” and “meth2” hasve a parameter called “self“. The "self
” parameter references the current instance of the class and is used by Python to access variables that belong to the class. For your purpose, just remember that all class methods must have the “self” parameter as the first parameter. Note that the class methods may have more than one parameter in addition to “self”.
Line 4): neptune = planet()
and uranus = planet()
Instantiate an object “neptune” and an object “uranus” in the class “planet”.
Line 5) neptune.meth1()
We call the method “meth1” which has a simple functionality (print function). The method “meth1” operates on object “neptune” to the left of the dot and accesses the class attribute “distanceNep”.
Line 6): uranus.meth2()
We call the method “meth2” that operates on object “uranus” to the left of the dot and accesses the class attribute ‘distanceUra’.
Method __init__ for Initialization of Objects (More Detailed Explanation)
Python has a method called __init__
that is used to initialize the object’s state. The __init__
method is run as soon as the object of a class is instantiated. The __init__
method initializes the attributes of the new class instance (object) we created.
Every class needs to have the __init__
method at the beginning of the class definition. The following code snippet illustrates the use of the __init__
method. We are again going to use our solar system as an example.
More About __init__ Method
Let us now write a more complex program using the __init__
method. This program defines parameters “distance”, “orbit”, and “revolution” in the class definition. Each of these parameter gets a different value for each class object “Mercury”, “Venus”, and “Earth”, when we instantiate the class objects.
PROGRAM EXAMPLE: __init__ CLASS METHOD – MORE DETAILED PROGRAM
>>> # Object Oriented Program to show use of class, object, and method
>>> class planet():
# __init__ method #1)
def __init__(self, distance, orbit, revolution): #1)
>>>
>>>
>>> # Instance Variables defined below. The data is unique to each instance.
self.distance = distance #2)
self.orbit = orbit
self.revolution = revolution
>>>
>>> # Object instantiation #3)
>>> Mercury = planet('37 million miles','88 days', '59 days')
>>> Venus = planet('65 million miles','225 days', '243 days')
>>> Earth = planet('93 million miles','365 days', '24 hours')
>>>
>>> # Print the attributes of each class objects #4)
>>> print('''Mercury is the first planet next to Sun.
Its distance from Sun is ''', Mercury.distance,'''
Mercury completes one orbit around the sun in ''', Mercury.orbit, '''
Mercury completes one revolution around its axis in ''', Mercury.revolution, '''
\nVenus is the second planet from Sun.
Its distance from Sun is ''', Venus.distance, '''
Venus completes one orbit around the sun in ''', Venus.orbit,'''
Venus completes one revolution around its axis in ''', Venus.revolution, '''
\nEarth is the third planet from Sun.
Its distance from Sun is ''', Earth.distance, '''
Earth completes one orbit around the sun in ''', Earth.orbit, '''
Earth completes one revolution around its axis in ''', Earth.revolution)
Mercury is the first planet next to Sun.
Its distance from Sun is 37 million miles
Mercury completes one orbit around the sun in 88 days
Mercury completes one revolution around its axis in 59 days
Venus is the second planet from Sun.
Its distance from Sun is 65 million miles
Venus completes one orbit around the sun in 225 days
Venus completes one revolution around its axis in 243 days
Earth is the third planet from Sun.
Its distance from Sun is 93 million miles
Earth completes one orbit around the sun in 365 days
Earth completes one revolution around its axis in 24 hours
>>>
__init__ Method Program Explanation (More Detail)
def __init__
(self, distance, orbit, revolution) The initializer method__init__
defines four parameters self, distance, orbit, and revolution.- Define instance attributes “distance”, “orbit”, and “revolution”. The attributes’ values are unique to each class instance.
- Mercury = planet(’37 million miles’,’88 days’, ’59 days’) In this step, the program instantiates three objects of the class planet with the instance variable values specific to each instance object defined in the parenthesis. In the case of the instance object ‘Mercury’, ‘distance’ = ‘37 million miles’, ‘orbit’ = ‘88 days’, and ‘revolution = ’59 days’. Venus = planet(’65 million miles’,’225 days’, ‘243 days’). In the case of object ‘Venus’, ‘distance’ = ‘65 million miles’, ‘orbit’ = ‘225 days’, and ‘revolution = ’243 days’. Earth = planet(’93 million miles’,’365 days’, ’24 hours’). In the case of object ‘Earth’, ‘distance’ = ‘93 million miles’, ‘orbit’ = ‘365 days’, and ‘revolution = ’24 hours’.
- Step 4) has a print statement that accesses the instance attributes “distance”, “orbit”, and “revolution” of each object of the class.
Note in step 2), the object instantiation uses the same order of parameters as in step 1)
Methods Associated with Data Type ‘string’ and ‘list’
From previous chapters, we know there are many types of data such as integers, strings, lists, dictionaries, etc. In OOP, each type of data type knows what operations can be done on a particular data type. To find out what operations (methods) are associated with a particular class instance object, the Python built-in function called dir()
can be used from the Python shell (IDLE).
As an example, let us find what methods are associated with data type str
. We use the function dir(str)
. The following is the IDLE output.
PROGRAM EXAMPLE: METHODS ASSOCIATED WITH DATA TYPE str
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__',
'__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__iter__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize',
'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index',
'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower',
'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
Methods Associated with Data Type list
Similarly, the methods associated with the data type list
can be found by the dir(list)
statement as below.
PROGRAM EXAMPLE: METHODS ASSOCIATED WITH DATA TYPE list
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__',
'__delitem__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__getitem__', '__gt__',
'__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
'__setattr__', '__setitem__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'clear', 'copy', 'count',
'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort']
>>>
From the above, we see that the methods associated with each data type (object) are specific to that object.
The methods that start and end with two underscores (__) are used by the Python interpreter internally. You can ignore them. The methods that do not have the double underscores are for the user to use in their programs.
To find out what a particular method does, you can use the help command. To illustrate the use of help()
, let us find out about the “capitalize” method for the str
data type as in the example below.
PROGRAM EXAMPLE: help() COMMAND
>>> help(str.capitalize)
Help on method_descriptor:
capitalize(self, /)
Return a capitalized version of the string.
More specifically, make the first character have upper case and the rest lower
case.
List Data Type Methods
As mentioned earlier, each data type has methods that belong to it. Using the Python built-in dir(list)
function on the Python IDLE shell, we saw a long list of methods for data type list. A few of the names of the methods in this list are append, insert, remove, etc.
Let us now develop a program to illustrate the use of a few methods associated with the list data type. Below is an example code to use the data type list‘s methods to insert an item between two items in the list. The program uses the append method to append an item at the end of the list.
Let us start with a list from the solar system example in the previous chapter. We define a list named “planets” below.
>>> planets = [‘mercury’, ‘venus’, ‘earth’, ‘mars’, ‘jupiter’]
insert Method and append Method for list Data Type
We will use the insert
method to insert the name “asteroid” between the items “mars” and “jupiter”. Then we will use the append
method to append “saturn” at the end of this list.
Note that in statement planets.insert
,
“planets” is the object and insert
is the method. As described earlier, the method insert after the dot operates on the object “planets” on the left side of the dot.
Note also the use of the index, which we introduced in an earlier chapter. In the “planets” list, the item “mercury” is index ‘0’, “venus” is index ‘1’, “earth” is index ‘2’, and “mars” is index ‘3’.
The statement planets.insert(4, ‘asteroid’)
inserts the word “asteroid” at index 4.
PROGRAM EXAMPLE: list DATA TYPE METHODS
>>> planets =['mercury', 'venus','earth','mars','jupiter']
>>> planets.insert(4, 'asteroid') # 1)
>>> planets
['mercury', 'venus', 'earth', 'mars', 'asteroid', 'jupiter']
>>> # Now append 'saturn' at the end of the list.
>>> planets.append('saturn') # 2)
>>> planets
['mercury', 'venus', 'earth', 'mars', 'asteroid', 'jupiter', 'saturn']
>>>
Explanation of the Program:
planets.insert(4, 'asteroid')
“insert” is a method associated with the data type list. This statement uses index = 4 to insert the word “asteroid” in the list “planet” at index 4.planets.append('saturn')
The statement uses the append method associated with the data type list to append an item at the end of the list
String Data Type Methods
In the section above, we used the function dir(str)
to view all built-in methods associated with data type str
.
The syntax to use these methods is as object.method()
.
The dot (.) tells Python that what follows the object
is the name of a method
.
Converting String Case
In the string methods list, there are methods named upper()
and lower()
. The functionality of the upper()
method is that it will convert all lowercase letters in the string to upper-case. The lower()
method will convert all letters in a string to lowercase.
In the program below, we define a string variable ‘Sun’ with a value “Sun is a star in the milky way”.
We will use upper()
method to convert the string to upper case. In the second part of the program, there is string named “NEPTUNE”. The program uses the lower()
method to convert all letters in the string to lower case.
>>> our_sun = (“Sun is a star in the milky way”)
In the second part of the program, a function call is made to method lower() and it returns a new string named ‘planet_lower_case’, which shows all letters have been changed to lower case as ‘neptune’.
PROGRAM EXAMPLE: STRING DATA TYPE METHODS USE CASE
our_sun = ("Sun is a star in the milky way") #1)
S = our_sun.upper() #2)
print(S)
SUN IS A STAR IN THE MILKY WAY #3)
S
'SUN IS A STAR IN THE MILKY WAY'
planet = "NEPTUNE" #4)
# Now use lower() method method to convert string to lower case.
planet_lower_case = planet.lower() #5)
print(planet_lower_case) $6)
neptune
- our_sun = (“Sun is a star in the milky way”) Define a steing variable named “our_sun” and assign it a value “Sun is a star in the milky way”.
- S = our_sun.upper() Define a variable named “S”. In this line, a function call is made to the method
upper()
associated with the object “our_sun”. The dot (.) tells Python that what follows the object is the name of a method. In this example case, theupper()
is the method and “our_sun” is the object. - print(S) The print function prints the contents of the string variable S”. Note that all characters in the string “S” have been converted to upper case.
- planet = “NEPTUNE” Define a string variable and call it “NEPTUNE”.
- planet_lower_case = planet.
Define a string variable named planet_lower_case. This statement makes a function call is made to the methodlower()
associated with the object “planet”. The dot (.) tells Python that what follows the object is the name of a method. In this example case, thelower()
is the method, and “planet” is the object. It returns a new string named “planet_lower_case”, which shows all letters have been changed to lowercase as “neptune”.lower()
find(), count(), capitalize() Methods and Parameters
In the section above, the program example created the methods list associated with the data type string created by the dir(str)
statement. In that methods list, there are methods ‘find
’, ‘count
’, and ‘capitalize
’. We will use these three methods as examples to explain the methods associated with the str
data type.
What Are Parameters in Methods
Before we do an example to illustrate the use of methods associated with data type str, let us introduce the concept of parameters for methods. Earlier, we introduced the object syntax as object. method().
We did not type anything between the open and closing parenthesis. The more general syntax is to include some parameters inside the parentheses. The general object syntax is:
object.method(parameters)
The parameter can be a substring of the string object.
In the program below, we will illustrate how these three methods associated with data type str
are used.
- Capitalize method: Returns a capitalized version of the string. Makes the first character upper-case and the rest lower-case. The string used in the program is “hawaii was admitted to the union on August 21, 1959”.
- Find method: If a substring is written within the parenthesis as a parameter, the find() method will find the substring in the string and returns the lowest index in the string, where the specified substring is found. The method returns -1 on failure (no substring found within the string). The substring is typed inside the parentheses as a parameter. In the program below, we will find the index of substring ‘York’.
- Count method: Returns the number of non-overlapping occurrences of a specified substring in the string. The substring is typed inside the parentheses as a parameter. In the program below, we will find the number of occurrences of substrings ‘31’ and ‘i’.
PROGRAM EXAMPLE: STRING DATA TYPE ‘capitalize’, ‘find’ AND ‘count’ METHODS
>>> # Program 1: Capitalize Method Example
>>> admissionDay = 'hawaii was admitted to the union on August 21, 1959.'
>>> # Capitalize 'h' in 'Hawaii'.
>>> capitalizedString = admissionDay.capitalize()
>>> print(capitalizedString)
Hawaii was admitted to the union on august 21, 1959.
>>>
>>> # Program 2: find() Method Example
>>> capital = 'New York capital is Albany'
>>> capitalIndex = capital.find('York')
>>> print(capitalIndex)
4
>>> Program 3: Count() Method Example
>>> cal = 'California is the 31st state of the union.'
>>> calNumber = cal.count('31')
>>> print(calNumber)
1
>>>
>>> cal.count('i')
3
>>>
Program 1: “admissionDay” is the object. capitalize() is the method. A function call is made to the method capitalize().
Program 2: Method “find” is used to find the index of substring “York” in the string “New York capital is Albany”. “York” is the method parameter. The method returns the index 4.
Program 3: Parameter is “31”.
Method ‘count(31)’ shows that the number of substrings “31’”in the string “California is the 31st state of the union.” is 1.
In the second part of the program, the parameter is “i”. There are three “i” in the string “California is the 31st state of the union.”
Copyright © 2019 – 2021 softwareprogramming4kids.com
All Rights Reserved