SlideShare a Scribd company logo
1 of 16
Download to read offline
What is Python?
• Python is a popular programming language. It was created by Guido
van Rossum, and released in 1991.
• It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
• What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify
files.
• Python can be used to handle big data and perform complex
mathematics.
• Python can be used for rapid prototyping, or for production-ready
software development.
• Why Python?
• Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs
with fewer lines than some other programming languages.
• Python runs on an interpreter system, meaning that code
can be executed as soon as it is written. This means that
prototyping can be very quick.
• Python can be treated in a procedural way, an object-
oriented way or a functional way.
• Object-oriented programming is a programming paradigm that provides
a means of structuring programs so that properties and behaviors are
bundled into individual objects.
• For instance, an object could represent a person with properties like a
name, age, and address and behaviors such as walking, talking,
breathing, and running.It could represent an email with properties like a
recipient list, subject, and body and behaviors like adding attachments
and sending.
• Put another way, object-oriented programming is an approach for
modeling concrete, real-world things, like cars, as well as relations
between things, like companies and employees, students and teachers,
and so on. OOP models real-world entities as software objects that have
some data associated with them and can perform certain functions.
• Classes are used to create user-defined data structures. Classes define
functions called methods, which identify the behaviors and actions that
an object created from the class can perform with its data.
• A class is a blueprint for how something should be defined. It doesn’t
actually contain any data. The Dog class specifies that a name and an age
are necessary for defining a dog, but it doesn’t contain the name or age of
any specific dog.
• While the class is the blueprint, an instance is an object that is built from a
class and contains real data. An instance of the Dog class is not a blueprint
anymore. It’s an actual dog with a name, like Miles, who’s four years old.
Class
• All class definitions start with the class keyword, which is followed by the name of
the class and a colon.
• Any code that is indented below the class definition is considered part of the
class’s body.
class Dog:
pass
• The body of the Dog class consists of a single statement: the pass keyword. pass is
often used as a placeholder indicating where code will eventually go. It allows
you to run this code without Python throwing an error.
• There are a number of properties that we can choose from, including name, age,
coat color, and breed.
• The properties that all Dog objects must have are defined in a method called
.__init__().
• Every time a new Dog object is created, .__init__() sets the initial state of the
object by assigning the values of the object’s properties. That is, .__init__()
initializes each new instance of the class.
• You can give .__init__() any number of parameters, but the first
parameter will always be a variable called self.
• When a new class instance is created, the instance is automatically
passed to the self parameter in .__init__() so that new attributes can
be defined on the object.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
• Notice that the .__init__() method’s signature is indented four spaces. The
body of the method is indented by eight spaces. This indentation is vitally
important.
• It tells Python that the .__init__() method belongs to the Dog class.
• In the body of .__init__(), there are two statements using the self variable:
1. self.name = name creates an attribute called name and assigns to it the
value of the name parameter.
2. self.age = age creates an attribute called age and assigns to it the value of
the age parameter.
Attributes created in .__init__() are called instance attributes.
An instance attribute’s value is specific to a particular instance of the class.
All Dog objects have a name and an age, but the values for the name and
age attributes will vary depending on the Dog instance.
• On the other hand, class attributes are attributes that have the same value for all
class instances. You can define a class attribute by assigning a value to a variable
name outside of .__init__().
class Dog:
# Class attribute
species = "Canis familiaris"
def __init__(self, name, age):
self.name = name
self.age = age
Class attributes are defined directly beneath the first line of the class name and are
indented by four spaces. They must always be assigned an initial value. When an
instance of the class is created, class attributes are automatically created and
assigned to their initial values.
• Creating a new object from a class is called instantiating an object. You can
instantiate a new Dog object by typing the name of the class, followed by
opening and closing
>>> Dog(“Rocky”,2)
You now have a new Dog object at 0x106702d30.
String of letters and numbers is a memory address that indicates where the
Dog object is stored in your computer’s memory.
>>> buddy = Dog("Buddy", 9)
>>> miles = Dog("Miles", 4)
This creates two new Dog instances—one for a nine-year-old dog named
Buddy and one for a four-year-old dog named Miles.
The Dog class’s .__init__() method has three parameters, so why are only
two arguments passed to it in the example?
When you instantiate a Dog object, Python creates a new instance and
passes it to the first parameter of .__init__(). This essentially removes the
self parameter, so you only need to worry about the name and age
parameters.
>>> buddy.name
'Buddy'
>>> buddy.age
9
>>> miles.name
'Miles'
>>> miles.age
4
>>> buddy.species
'Canis familiaris'
Instance Methods
• Instance methods are functions that are defined inside a class and can only be
called from an instance of that class. Just like .__init__(), an instance method’s
first parameter is always self.
class Dog:
species = "Canis familiaris"
def __init__(self, name, age):
self.name = name
self.age = age
# Instance method
def description(self):
return f"{self.name} is {self.age} years old"
# Another instance method
def speak(self, sound):
return f"{self.name} says {sound}"
• This Dog class has two instance methods:
• .description() returns a string displaying the name and age of the dog.
• .speak() has one parameter called sound and returns a string containing
the dog’s name and the sound the dog makes.
• Save the modified Dog class to a file called dog.py and press F5 to run the
program.
>>> miles = Dog("Miles", 4)
>>> miles.description()
'Miles is 4 years old'
>>> miles.speak("Woof Woof")
'Miles says Woof Woof'
>>> miles.speak("Bow Wow")
'Miles says Bow Wow'
Inherit From Other Classes in Python
• Inheritance is the process by which one class takes on the attributes and methods of
another. Newly formed classes are called child classes, and the classes that child classes
are derived from are called parent classes.
• Child classes can override or extend the attributes and methods of parent classes. In
other words, child classes inherit all of the parent’s attributes and methods but can also
specify attributes and methods that are unique to themselves.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the
printname method:
x = Person("John", "Doe")
x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send
the parent class as a parameter when creating the child class:
class Student(Person):
pass
Use the pass keyword when you do not want to add any other properties or methods to the
class.
x = Student("Mike", "Olsen")
x.printname()
Add the __init__() Function
So far we have created a child class that inherits the properties and methods from its parent.
We want to add the __init__() function to the child class (instead of the pass keyword).
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the parent's
__init__() function.
Now we have successfully added the __init__() function, and kept the inheritance of the
parent class, and we are ready to add functionality in the __init__() function
• Python also has a super() function that will make the child class inherit all
the methods and properties from its parent:
• class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
• By using the super() function, you do not have to use the name of the
parent element, it will automatically inherit the methods and properties
from its parent.
• class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
• class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
• class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname,
self.lastname, "to the class of",
self.graduationyear)

More Related Content

Similar to python note.pdf

Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Bhanwar Singh Meena
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc csKALAISELVI P
 
Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python Jean Carlo Machado
 
Objective-C talk
Objective-C talkObjective-C talk
Objective-C talkbradringel
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2Ahmad Hussein
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
CS 151 Classes lecture
CS 151 Classes lectureCS 151 Classes lecture
CS 151 Classes lectureRudy Martinez
 
Regex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overlodingRegex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overlodingsangumanikesh
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programmingshinyduela
 
Object in python tells about object oriented programming in python
Object in python tells about object oriented programming in pythonObject in python tells about object oriented programming in python
Object in python tells about object oriented programming in pythonReshmiShaw2
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritancemcollison
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 

Similar to python note.pdf (20)

Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
 
Object concepts
Object conceptsObject concepts
Object concepts
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
S12.s01 - Material TP.pdf
S12.s01 - Material TP.pdfS12.s01 - Material TP.pdf
S12.s01 - Material TP.pdf
 
Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python Domain Driven Design Made Functional with Python
Domain Driven Design Made Functional with Python
 
Objective-C talk
Objective-C talkObjective-C talk
Objective-C talk
 
Python introduction 2
Python introduction 2Python introduction 2
Python introduction 2
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
CS 151 Classes lecture
CS 151 Classes lectureCS 151 Classes lecture
CS 151 Classes lecture
 
Regex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overlodingRegex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overloding
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
ACM init() Day 5
ACM init() Day 5ACM init() Day 5
ACM init() Day 5
 
Lecture 1 - Objects and classes
Lecture 1 - Objects and classesLecture 1 - Objects and classes
Lecture 1 - Objects and classes
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Object concepts
Object conceptsObject concepts
Object concepts
 
Object in python tells about object oriented programming in python
Object in python tells about object oriented programming in pythonObject in python tells about object oriented programming in python
Object in python tells about object oriented programming in python
 
Pi j3.1 inheritance
Pi j3.1 inheritancePi j3.1 inheritance
Pi j3.1 inheritance
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 

Recently uploaded

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 

Recently uploaded (20)

BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 

python note.pdf

  • 1. What is Python? • Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. • It is used for: • web development (server-side), • software development, • mathematics, • system scripting. • What can Python do? • Python can be used on a server to create web applications. • Python can be used alongside software to create workflows. • Python can connect to database systems. It can also read and modify files. • Python can be used to handle big data and perform complex mathematics. • Python can be used for rapid prototyping, or for production-ready software development.
  • 2. • Why Python? • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). • Python has a simple syntax similar to the English language. • Python has syntax that allows developers to write programs with fewer lines than some other programming languages. • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. • Python can be treated in a procedural way, an object- oriented way or a functional way.
  • 3. • Object-oriented programming is a programming paradigm that provides a means of structuring programs so that properties and behaviors are bundled into individual objects. • For instance, an object could represent a person with properties like a name, age, and address and behaviors such as walking, talking, breathing, and running.It could represent an email with properties like a recipient list, subject, and body and behaviors like adding attachments and sending. • Put another way, object-oriented programming is an approach for modeling concrete, real-world things, like cars, as well as relations between things, like companies and employees, students and teachers, and so on. OOP models real-world entities as software objects that have some data associated with them and can perform certain functions.
  • 4. • Classes are used to create user-defined data structures. Classes define functions called methods, which identify the behaviors and actions that an object created from the class can perform with its data. • A class is a blueprint for how something should be defined. It doesn’t actually contain any data. The Dog class specifies that a name and an age are necessary for defining a dog, but it doesn’t contain the name or age of any specific dog. • While the class is the blueprint, an instance is an object that is built from a class and contains real data. An instance of the Dog class is not a blueprint anymore. It’s an actual dog with a name, like Miles, who’s four years old.
  • 5. Class • All class definitions start with the class keyword, which is followed by the name of the class and a colon. • Any code that is indented below the class definition is considered part of the class’s body. class Dog: pass • The body of the Dog class consists of a single statement: the pass keyword. pass is often used as a placeholder indicating where code will eventually go. It allows you to run this code without Python throwing an error. • There are a number of properties that we can choose from, including name, age, coat color, and breed. • The properties that all Dog objects must have are defined in a method called .__init__(). • Every time a new Dog object is created, .__init__() sets the initial state of the object by assigning the values of the object’s properties. That is, .__init__() initializes each new instance of the class.
  • 6. • You can give .__init__() any number of parameters, but the first parameter will always be a variable called self. • When a new class instance is created, the instance is automatically passed to the self parameter in .__init__() so that new attributes can be defined on the object. class Dog: def __init__(self, name, age): self.name = name self.age = age
  • 7. • Notice that the .__init__() method’s signature is indented four spaces. The body of the method is indented by eight spaces. This indentation is vitally important. • It tells Python that the .__init__() method belongs to the Dog class. • In the body of .__init__(), there are two statements using the self variable: 1. self.name = name creates an attribute called name and assigns to it the value of the name parameter. 2. self.age = age creates an attribute called age and assigns to it the value of the age parameter. Attributes created in .__init__() are called instance attributes. An instance attribute’s value is specific to a particular instance of the class. All Dog objects have a name and an age, but the values for the name and age attributes will vary depending on the Dog instance.
  • 8. • On the other hand, class attributes are attributes that have the same value for all class instances. You can define a class attribute by assigning a value to a variable name outside of .__init__(). class Dog: # Class attribute species = "Canis familiaris" def __init__(self, name, age): self.name = name self.age = age Class attributes are defined directly beneath the first line of the class name and are indented by four spaces. They must always be assigned an initial value. When an instance of the class is created, class attributes are automatically created and assigned to their initial values.
  • 9. • Creating a new object from a class is called instantiating an object. You can instantiate a new Dog object by typing the name of the class, followed by opening and closing >>> Dog(“Rocky”,2) You now have a new Dog object at 0x106702d30. String of letters and numbers is a memory address that indicates where the Dog object is stored in your computer’s memory. >>> buddy = Dog("Buddy", 9) >>> miles = Dog("Miles", 4) This creates two new Dog instances—one for a nine-year-old dog named Buddy and one for a four-year-old dog named Miles. The Dog class’s .__init__() method has three parameters, so why are only two arguments passed to it in the example? When you instantiate a Dog object, Python creates a new instance and passes it to the first parameter of .__init__(). This essentially removes the self parameter, so you only need to worry about the name and age parameters.
  • 10. >>> buddy.name 'Buddy' >>> buddy.age 9 >>> miles.name 'Miles' >>> miles.age 4 >>> buddy.species 'Canis familiaris'
  • 11. Instance Methods • Instance methods are functions that are defined inside a class and can only be called from an instance of that class. Just like .__init__(), an instance method’s first parameter is always self. class Dog: species = "Canis familiaris" def __init__(self, name, age): self.name = name self.age = age # Instance method def description(self): return f"{self.name} is {self.age} years old" # Another instance method def speak(self, sound): return f"{self.name} says {sound}"
  • 12. • This Dog class has two instance methods: • .description() returns a string displaying the name and age of the dog. • .speak() has one parameter called sound and returns a string containing the dog’s name and the sound the dog makes. • Save the modified Dog class to a file called dog.py and press F5 to run the program. >>> miles = Dog("Miles", 4) >>> miles.description() 'Miles is 4 years old' >>> miles.speak("Woof Woof") 'Miles says Woof Woof' >>> miles.speak("Bow Wow") 'Miles says Bow Wow'
  • 13. Inherit From Other Classes in Python • Inheritance is the process by which one class takes on the attributes and methods of another. Newly formed classes are called child classes, and the classes that child classes are derived from are called parent classes. • Child classes can override or extend the attributes and methods of parent classes. In other words, child classes inherit all of the parent’s attributes and methods but can also specify attributes and methods that are unique to themselves. class Person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) #Use the Person class to create an object, and then execute the printname method: x = Person("John", "Doe") x.printname()
  • 14. Create a Child Class To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class: class Student(Person): pass Use the pass keyword when you do not want to add any other properties or methods to the class. x = Student("Mike", "Olsen") x.printname() Add the __init__() Function So far we have created a child class that inherits the properties and methods from its parent. We want to add the __init__() function to the child class (instead of the pass keyword). class Student(Person): def __init__(self, fname, lname): #add properties etc. When you add the __init__() function, the child class will no longer inherit the parent's __init__() function. Now we have successfully added the __init__() function, and kept the inheritance of the parent class, and we are ready to add functionality in the __init__() function
  • 15. • Python also has a super() function that will make the child class inherit all the methods and properties from its parent: • class Student(Person): def __init__(self, fname, lname): super().__init__(fname, lname) • By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent. • class Student(Person): def __init__(self, fname, lname): super().__init__(fname, lname) self.graduationyear = 2019 • class Student(Person): def __init__(self, fname, lname, year): super().__init__(fname, lname) self.graduationyear = year x = Student("Mike", "Olsen", 2019)
  • 16. • class Student(Person): def __init__(self, fname, lname, year): super().__init__(fname, lname) self.graduationyear = year def welcome(self): print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)