SlideShare a Scribd company logo
1 of 27
Download to read offline
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

What's hot

Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 

What's hot (20)

Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 
AmI 2017 - Python basics
AmI 2017 - Python basicsAmI 2017 - Python basics
AmI 2017 - Python basics
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)Rails workshop for Java people (September 2015)
Rails workshop for Java people (September 2015)
 
PHP Strings and Patterns
PHP Strings and PatternsPHP Strings and Patterns
PHP Strings and Patterns
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Variables In Php 1
Variables In Php 1Variables In Php 1
Variables In Php 1
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Hashes
HashesHashes
Hashes
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
 
Python 101
Python 101Python 101
Python 101
 
Clean Code Tips (Day 1 )
Clean Code Tips (Day 1 )Clean Code Tips (Day 1 )
Clean Code Tips (Day 1 )
 
PHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with thisPHP Powerpoint -- Teach PHP with this
PHP Powerpoint -- Teach PHP with this
 
Ruby cheat sheet
Ruby cheat sheetRuby cheat sheet
Ruby cheat sheet
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic Operations
 

Similar to Python introduction 2

Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineering
IRAH34
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 

Similar to Python introduction 2 (20)

Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineering
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 
Python basic
Python basicPython basic
Python basic
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181The Ring programming language version 1.5.2 book - Part 6 of 181
The Ring programming language version 1.5.2 book - Part 6 of 181
 
Python Novice to Ninja
Python Novice to NinjaPython Novice to Ninja
Python Novice to Ninja
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
 
Python Part 2
Python Part 2Python Part 2
Python Part 2
 

More from Ahmad Hussein (6)

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

Recently uploaded

Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
nirzagarg
 
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
nirzagarg
 
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
gajnagarg
 
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi ArabiaIn Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
ahmedjiabur940
 
Kalyani ? Call Girl in Kolkata | Service-oriented sexy call girls 8005736733 ...
Kalyani ? Call Girl in Kolkata | Service-oriented sexy call girls 8005736733 ...Kalyani ? Call Girl in Kolkata | Service-oriented sexy call girls 8005736733 ...
Kalyani ? Call Girl in Kolkata | Service-oriented sexy call girls 8005736733 ...
HyderabadDolls
 
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
gajnagarg
 
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
nirzagarg
 
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
vexqp
 
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
HyderabadDolls
 
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
gajnagarg
 

Recently uploaded (20)

Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
Top profile Call Girls In Bihar Sharif [ 7014168258 ] Call Me For Genuine Mod...
 
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
High Profile Call Girls Service in Jalore { 9332606886 } VVIP NISHA Call Girl...
 
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Satna [ 7014168258 ] Call Me For Genuine Models We ...
 
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
Top profile Call Girls In Latur [ 7014168258 ] Call Me For Genuine Models We ...
 
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With OrangePredicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
Predicting HDB Resale Prices - Conducting Linear Regression Analysis With Orange
 
Vastral Call Girls Book Now 7737669865 Top Class Escort Service Available
Vastral Call Girls Book Now 7737669865 Top Class Escort Service AvailableVastral Call Girls Book Now 7737669865 Top Class Escort Service Available
Vastral Call Girls Book Now 7737669865 Top Class Escort Service Available
 
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi ArabiaIn Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
In Riyadh ((+919101817206)) Cytotec kit @ Abortion Pills Saudi Arabia
 
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
TrafficWave Generator Will Instantly drive targeted and engaging traffic back...
 
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
SAC 25 Final National, Regional & Local Angel Group Investing Insights 2024 0...
 
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
💞 Safe And Secure Call Girls Agra Call Girls Service Just Call 🍑👄6378878445 🍑...
 
Kalyani ? Call Girl in Kolkata | Service-oriented sexy call girls 8005736733 ...
Kalyani ? Call Girl in Kolkata | Service-oriented sexy call girls 8005736733 ...Kalyani ? Call Girl in Kolkata | Service-oriented sexy call girls 8005736733 ...
Kalyani ? Call Girl in Kolkata | Service-oriented sexy call girls 8005736733 ...
 
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Nandurbar [ 7014168258 ] Call Me For Genuine Models...
 
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
Top profile Call Girls In Begusarai [ 7014168258 ] Call Me For Genuine Models...
 
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
怎样办理圣地亚哥州立大学毕业证(SDSU毕业证书)成绩单学校原版复制
 
Digital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham WareDigital Transformation Playbook by Graham Ware
Digital Transformation Playbook by Graham Ware
 
Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...
Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...
Gomti Nagar & best call girls in Lucknow | 9548273370 Independent Escorts & D...
 
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
Sealdah % High Class Call Girls Kolkata - 450+ Call Girl Cash Payment 8005736...
 
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
Top profile Call Girls In Chandrapur [ 7014168258 ] Call Me For Genuine Model...
 
Top Call Girls in Balaghat 9332606886Call Girls Advance Cash On Delivery Ser...
Top Call Girls in Balaghat  9332606886Call Girls Advance Cash On Delivery Ser...Top Call Girls in Balaghat  9332606886Call Girls Advance Cash On Delivery Ser...
Top Call Girls in Balaghat 9332606886Call Girls Advance Cash On Delivery Ser...
 

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.