SlideShare a Scribd company logo
Introduction to Python -2
Ahmad Hussein
ahmadhussein.ah7@gmail.com
Classes
Class Declaration
• The simplest class possible is shown in the following example:
class Person:
pass # An empty block
Class Methods
• The self:
Class methods have only one specific difference from ordinary functions.
they must have an extra first name that has to be added to the beginning
of the parameter list, but you do not give a value for this parameter when
you call the method, Python will provide it. This particular variable refers to
the object itself, and by convention, it is given the name self.
The self in Python is equivalent to the this pointer in C++ and the this reference in
Java and C#.
Class Methods
class Person:
def say_hi(self):
print('Hello, how are you?')
p = Person()
p.say_hi()
# Hello, how are you?
The __init__ method
• The __init__ method is run as soon as an object of a class is created.
The method is useful to do any initialization you want to do with your
object.
class Person:
def __init__(self, name):
self.name = name
def say_hi(self):
print('Hello, my name is', self.name)
p = Person(‘Yasser')
p.say_hi()
# Hello, my name is Yasser
Class And Object Variables
• Class variables are shared - they can be accessed by all instances of
that class.
• Object variables are owned by each individual object/instance of the
class. In this case, each object has its own copy of the field i.e. they
are not shared and are not related in any way to the field by the same
name in a different instance.
Class And Object Variables
class Robot:
"""Represents a robot, with a name."""
# A class variable, counting the number of robots
population = 0
def __init__(self, name):
"""Initializes the data."""
self.name = name
print("(Initializing {})".format(self.name))
# When this person is created, the robot
# adds to the population
Robot.population += 1
Class And Object Variables
def die(self):
"""I am dying."""
print("{} is being destroyed!".format(self.name))
Robot.population -= 1
def say_hi(self):
print("Greetings, my masters call me {}.".format(self.name))
@classmethod
def how_many(cls):
"""Prints the current population."""
print("We have {:d} robots.".format(cls.population))
Class And Object Variables
droid1 = Robot("R2-D2")
droid1.say_hi()
Robot.how_many()
droid2 = Robot("C-3PO")
droid2.say_hi()
Robot.how_many()
droid1.die()
droid2.die()
Robot.how_many()
Class And Object Variables
Output
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.
(Initializing C-3PO)
Greetings, my masters call me C-3PO.
We have 2 robots.
R2-D2 is being destroyed!
C-3PO is being destroyed!
We have 0 robots.
Inheritance
Inheritance
class SchoolMember:
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember: {})'.format(self.name))
def tell(self):
print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")
Inheritance
class Teacher(SchoolMember):
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print('(Initialized Teacher: {})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Salary: "{:d}"'.format(self.salary))
Inheritance
class Student(SchoolMember):
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print('(Initialized Student: {})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Marks: "{:d}"'.format(self.marks))
Inheritance
t = Teacher('Ahmad', 40, 1234)
s = Student('Khaled', 25, 75)
members = [t, s]
for member in members:
# Works for both Teachers and Students
member.tell()
Inheritance
Output:
(Initialized SchoolMember: Ahmad)
(Initialized Teacher: Ahmad)
(Initialized SchoolMember: Khaled)
(Initialized Student: Khaled)
Name:"Ahmad" Age:"40" Salary: "1234"
Name:"Khaled" Age:"25" Marks: "75"
Input and Output
Input from user
text = input("Enter text: ")
# Enter text: Ahmad
Files
poem = '''
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
'''
# Open for 'w'riting
f = open('poem.txt', 'w')
# Write text to file
f.write(poem)
# Close the file
f.close()
Files
# If no mode is specified,
# 'r'ead mode is assumed by default
f = open('poem.txt')
while True:
line = f.readline()
# Zero length indicates EOF
if len(line) == 0:
break
print(line, end='')
# close the file
f.close()
Files
Output
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
Exceptions
Errors
• Consider a simple print function call. What if we misspelt print as
Print? Note the capitalization. In this case, Python raises a syntax
error.
Print("Hello World")
# NameError: name 'Print' is not defined
print("Hello World")
# Hello World
Exceptions
• Exceptions occur when exceptional situations occur in your program.
For example, what if you are going to read a file and the file does not
exist? Or what if you accidentally deleted it when the program was
running? Such situations are handled using exceptions.
10 * (1/0)
# ZeroDivisionError: division by zero
Handling Exceptions
try:
10 * (1/0)
except ZeroDivisionError:
print("Can't division by zero")
# Can't division by zero
Handling Exceptions
try:
x = int(input("Please enter a number: "))
except ValueError:
print("Oops! That was no valid number.")
# Please enter a number: df
# Oops! That was no valid number.

More Related Content

PDF
Python introduction 1
PDF
Ruby 2: some new things
ODP
Python an-intro - odp
PDF
Ruby Classes
PDF
AmI 2016 - Python basics
PDF
How to write test in Django
PDF
AmI 2015 - Python basics
PPTX
Python Workshop
Python introduction 1
Ruby 2: some new things
Python an-intro - odp
Ruby Classes
AmI 2016 - Python basics
How to write test in Django
AmI 2015 - Python basics
Python Workshop

What's hot (20)

PDF
Ruby - Uma Introdução
PDF
WordCamp Portland 2018: PHP for WordPress
PDF
Datatypes in python
KEY
Desarrollando aplicaciones web en minutos
PPTX
Learn python in 20 minutes
PDF
AmI 2017 - Python basics
PPTX
Python 101++: Let's Get Down to Business!
PDF
Rails workshop for Java people (September 2015)
PPTX
PHP Strings and Patterns
PDF
Learn 90% of Python in 90 Minutes
PDF
Strings in Python
PPTX
Ruby from zero to hero
PDF
Python 101
PDF
Clean Code Tips (Day 1 )
PPTX
PHP Powerpoint -- Teach PHP with this
PDF
Ruby cheat sheet
PDF
Working with text, Regular expressions
PDF
Matlab and Python: Basic Operations
Ruby - Uma Introdução
WordCamp Portland 2018: PHP for WordPress
Datatypes in python
Desarrollando aplicaciones web en minutos
Learn python in 20 minutes
AmI 2017 - Python basics
Python 101++: Let's Get Down to Business!
Rails workshop for Java people (September 2015)
PHP Strings and Patterns
Learn 90% of Python in 90 Minutes
Strings in Python
Ruby from zero to hero
Python 101
Clean Code Tips (Day 1 )
PHP Powerpoint -- Teach PHP with this
Ruby cheat sheet
Working with text, Regular expressions
Matlab and Python: Basic Operations
Ad

Similar to Python introduction 2 (20)

PPTX
Class, object and inheritance in python
PPTX
Python Workshop - Learn Python the Hard Way
PPTX
Python programming computer science and engineering
PPTX
UNIT-5 object oriented programming lecture
PPT
Spsl v unit - final
PPT
Spsl vi unit final
PPTX
Object Oriented Programming in Python.pptx
PDF
Postobjektové programovanie v Ruby
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PDF
Python-Cheat-Sheet.pdf
PDF
Python basic
KEY
Intro to Ruby - Twin Cities Code Camp 7
PPT
Object Orientation vs. Functional Programming in Python
PPTX
Polymorphism.pptx
PDF
The Ring programming language version 1.5.2 book - Part 6 of 181
PDF
Python Novice to Ninja
PPTX
Python Details Functions Description.pptx
PDF
Introduction to Python for Plone developers
Class, object and inheritance in python
Python Workshop - Learn Python the Hard Way
Python programming computer science and engineering
UNIT-5 object oriented programming lecture
Spsl v unit - final
Spsl vi unit final
Object Oriented Programming in Python.pptx
Postobjektové programovanie v Ruby
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Python-Cheat-Sheet.pdf
Python basic
Intro to Ruby - Twin Cities Code Camp 7
Object Orientation vs. Functional Programming in Python
Polymorphism.pptx
The Ring programming language version 1.5.2 book - Part 6 of 181
Python Novice to Ninja
Python Details Functions Description.pptx
Introduction to Python for Plone developers
Ad

More from Ahmad Hussein (6)

PDF
Knowledge Representation Methods
PDF
Knowledge-Base Systems Homework - 2019
PDF
Design Patterns
PDF
Knowledge based systems homework
PDF
Expert system with python -2
PDF
Expert System With Python -1
Knowledge Representation Methods
Knowledge-Base Systems Homework - 2019
Design Patterns
Knowledge based systems homework
Expert system with python -2
Expert System With Python -1

Recently uploaded (20)

PPTX
Moving the Public Sector (Government) to a Digital Adoption
PDF
Foundation of Data Science unit number two notes
PDF
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PPTX
Major-Components-ofNKJNNKNKNKNKronment.pptx
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
PPTX
Introduction-to-Cloud-ComputingFinal.pptx
PDF
Fluorescence-microscope_Botany_detailed content
PDF
Clinical guidelines as a resource for EBP(1).pdf
PPTX
05. PRACTICAL GUIDE TO MICROSOFT EXCEL.pptx
PDF
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
PDF
Galatica Smart Energy Infrastructure Startup Pitch Deck
PPTX
STUDY DESIGN details- Lt Col Maksud (21).pptx
PPTX
Introduction to Knowledge Engineering Part 1
PDF
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
PDF
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
PPTX
Data_Analytics_and_PowerBI_Presentation.pptx
PPTX
IBA_Chapter_11_Slides_Final_Accessible.pptx
PPTX
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
PPT
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
Moving the Public Sector (Government) to a Digital Adoption
Foundation of Data Science unit number two notes
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
Major-Components-ofNKJNNKNKNKNKronment.pptx
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
Introduction-to-Cloud-ComputingFinal.pptx
Fluorescence-microscope_Botany_detailed content
Clinical guidelines as a resource for EBP(1).pdf
05. PRACTICAL GUIDE TO MICROSOFT EXCEL.pptx
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
Galatica Smart Energy Infrastructure Startup Pitch Deck
STUDY DESIGN details- Lt Col Maksud (21).pptx
Introduction to Knowledge Engineering Part 1
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
Data_Analytics_and_PowerBI_Presentation.pptx
IBA_Chapter_11_Slides_Final_Accessible.pptx
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn

Python introduction 2

  • 1. Introduction to Python -2 Ahmad Hussein ahmadhussein.ah7@gmail.com
  • 3. Class Declaration • The simplest class possible is shown in the following example: class Person: pass # An empty block
  • 4. Class Methods • The self: Class methods have only one specific difference from ordinary functions. they must have an extra first name that has to be added to the beginning of the parameter list, but you do not give a value for this parameter when you call the method, Python will provide it. This particular variable refers to the object itself, and by convention, it is given the name self. The self in Python is equivalent to the this pointer in C++ and the this reference in Java and C#.
  • 5. Class Methods class Person: def say_hi(self): print('Hello, how are you?') p = Person() p.say_hi() # Hello, how are you?
  • 6. The __init__ method • The __init__ method is run as soon as an object of a class is created. The method is useful to do any initialization you want to do with your object. class Person: def __init__(self, name): self.name = name def say_hi(self): print('Hello, my name is', self.name) p = Person(‘Yasser') p.say_hi() # Hello, my name is Yasser
  • 7. Class And Object Variables • Class variables are shared - they can be accessed by all instances of that class. • Object variables are owned by each individual object/instance of the class. In this case, each object has its own copy of the field i.e. they are not shared and are not related in any way to the field by the same name in a different instance.
  • 8. Class And Object Variables class Robot: """Represents a robot, with a name.""" # A class variable, counting the number of robots population = 0 def __init__(self, name): """Initializes the data.""" self.name = name print("(Initializing {})".format(self.name)) # When this person is created, the robot # adds to the population Robot.population += 1
  • 9. Class And Object Variables def die(self): """I am dying.""" print("{} is being destroyed!".format(self.name)) Robot.population -= 1 def say_hi(self): print("Greetings, my masters call me {}.".format(self.name)) @classmethod def how_many(cls): """Prints the current population.""" print("We have {:d} robots.".format(cls.population))
  • 10. Class And Object Variables droid1 = Robot("R2-D2") droid1.say_hi() Robot.how_many() droid2 = Robot("C-3PO") droid2.say_hi() Robot.how_many() droid1.die() droid2.die() Robot.how_many()
  • 11. Class And Object Variables Output (Initializing R2-D2) Greetings, my masters call me R2-D2. We have 1 robots. (Initializing C-3PO) Greetings, my masters call me C-3PO. We have 2 robots. R2-D2 is being destroyed! C-3PO is being destroyed! We have 0 robots.
  • 13. Inheritance class SchoolMember: def __init__(self, name, age): self.name = name self.age = age print('(Initialized SchoolMember: {})'.format(self.name)) def tell(self): print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")
  • 14. Inheritance class Teacher(SchoolMember): def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print('(Initialized Teacher: {})'.format(self.name)) def tell(self): SchoolMember.tell(self) print('Salary: "{:d}"'.format(self.salary))
  • 15. Inheritance class Student(SchoolMember): def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print('(Initialized Student: {})'.format(self.name)) def tell(self): SchoolMember.tell(self) print('Marks: "{:d}"'.format(self.marks))
  • 16. Inheritance t = Teacher('Ahmad', 40, 1234) s = Student('Khaled', 25, 75) members = [t, s] for member in members: # Works for both Teachers and Students member.tell()
  • 17. Inheritance Output: (Initialized SchoolMember: Ahmad) (Initialized Teacher: Ahmad) (Initialized SchoolMember: Khaled) (Initialized Student: Khaled) Name:"Ahmad" Age:"40" Salary: "1234" Name:"Khaled" Age:"25" Marks: "75"
  • 19. Input from user text = input("Enter text: ") # Enter text: Ahmad
  • 20. Files poem = ''' Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' # Open for 'w'riting f = open('poem.txt', 'w') # Write text to file f.write(poem) # Close the file f.close()
  • 21. Files # If no mode is specified, # 'r'ead mode is assumed by default f = open('poem.txt') while True: line = f.readline() # Zero length indicates EOF if len(line) == 0: break print(line, end='') # close the file f.close()
  • 22. Files Output Programming is fun When the work is done if you wanna make your work also fun: use Python!
  • 24. Errors • Consider a simple print function call. What if we misspelt print as Print? Note the capitalization. In this case, Python raises a syntax error. Print("Hello World") # NameError: name 'Print' is not defined print("Hello World") # Hello World
  • 25. Exceptions • Exceptions occur when exceptional situations occur in your program. For example, what if you are going to read a file and the file does not exist? Or what if you accidentally deleted it when the program was running? Such situations are handled using exceptions. 10 * (1/0) # ZeroDivisionError: division by zero
  • 26. Handling Exceptions try: 10 * (1/0) except ZeroDivisionError: print("Can't division by zero") # Can't division by zero
  • 27. Handling Exceptions try: x = int(input("Please enter a number: ")) except ValueError: print("Oops! That was no valid number.") # Please enter a number: df # Oops! That was no valid number.