SlideShare a Scribd company logo
Python Advance
• Class
• Exception handling
• Generators
• CGI
• Databases
• Tkinter(GUI)
• Regular expression
• Email sending(SMTP)
Object-oriented language
• Python is a multi-paradigm programming language. Meaning, it supports
different programming approach.
• One of the popular approach to solve a programming problem is by
creating objects. This is known as Object-Oriented Programming (OOP).
• An object has two characteristics:
• attributes
• Behavior
• The concept of OOP in Python focuses on creating reusable code. This
concept is also known as DRY (Don't Repeat Yourself).
• In Python, the concept of OOP follows some basic principles:
• Inheritance-A process of using details from a new class without modifying
existing class.
• Encapsulation-Hiding the private details of a class from other objects.
• Polymorphism-A concept of using common operation in different ways for
different data input.
Object-oriented language
• Class − A user-defined prototype for an object that defines
a set of attributes that characterize any object of the class.
The attributes are data members (class variables and
instance variables) and methods, accessed via dot notation.
• Class variable − A variable that is shared by all instances of
a class. Class variables are defined within a class but
outside any of the class's methods. Class variables are not
used as frequently as instance variables are.
• Data member − A class variable or instance variable that
holds data associated with a class and its objects.
• Function overloading − The assignment of more than one
behavior to a particular function. The operation performed
varies by the types of objects or arguments involved.
• Instance variable − A variable that is defined inside a method and
belongs only to the current instance of a class.
• Inheritance − The transfer of the characteristics of a class to other
classes that are derived from it.
• Instance − An individual object of a certain class. An object obj that
belongs to a class Circle, for example, is an instance of the class
Circle.
• Instantiation − The creation of an instance of a class.
• Method − A special kind of function that is defined in a class
definition.
• Object − A unique instance of a data structure that is defined by its
class. An object comprises both data members (class variables and
instance variables) and methods.
• Operator overloading − The assignment of more than one function
to a particular operator.
• In Python, the concept of OOP follows some basic
principles:
• Inheritance-A process of using details from a new
class without modifying existing class.
• Abstraction-Hiding the private details of a class
from other objects.
• Polymorphism-A concept of using common
operation in different ways for different data
input.
• Name Notation Behaviour
name Public Can be accessed from inside
• and outside
_name Protected Like a public member,
• but they shouldn't be
• directly accessed from
• outside.
__name Private Can't be seen and accessed
• from outsid’
Creating Classes
• The class statement creates a new class
definition. The name of the class immediately
follows the keyword class followed by a colon as
follows −
• class ClassName:
• class body
• which can be accessed via ClassName.__doc__.
• The class_suite consists of all the component
statements defining class members, data
attributes and functions.
• Ex.
• class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
Creating Instance Objects
• Creating Instance Objects
• class emp1 = Employee("Zara", 2000)
• emp2 = Employee("Manni", 5000)
• Accessing Attributes
• emp1.displayEmployee()
emp2.displayEmployee()
• print ("Total Employee”,Employee.empCount)
• Ex.
• class Employee:
• 'Common base class for all employees' empCount = 0
• def __init__(self, name, salary):
• self.name = name
• self.salary = salary
• Employee.empCount += 1
• def displayCount(self):
• print ("Total Employee %d" % Employee.empCount)
• def displayEmployee(self):
• print ("Name : ", self.name, ", Salary: ", self.salary)
• #This would create first object of Employee class"
• emp1 = Employee("Zara", 2000)
• #This would create second object of Employee class“
• emp2 = Employee("Manni", 5000)
• emp1.displayEmployee()
• emp2.displayEmployee()
• print ("Total Employee %d" % Employee.empCount)
Access Attribute
• access attributes
• The getattr(obj, name[, default]) − to access the attribute of
object.
• The hasattr(obj,name) − to check if an attribute exists or
not.
• The setattr(obj,name,value) − to set an attribute. If
attribute does not exist, then it would be created.
• The delattr(obj, name) − to delete an attribute.
In Built Class Attribute
• Every Python class keeps following built-in attributes and
they can be accessed using dot operator like any other
attribute −
• __dict__ − Dictionary containing the class's namespace.
• __doc__ − Class documentation string or none, if
undefined.
• __module__ − Module name in which the class is defined.
This attribute is "__main__" in interactive mode.
• __bases__ − A possibly empty tuple containing the base
classes, in the order of their occurrence in the base class
list.
• class Employee:
• 'Common base class for all employees'
• empCount = 0
• def __init__(self, name, salary):
• self.name = name
• self.salary = salary
• Employee.empCount += 1
• def displayCount(self):
• print ("Total Employee %d" % Employee.empCount)
• def displayEmployee(self):
• print ("Name : ", self.name, ", Salary: ", self.salary)
• emp1 = Employee("Zara", 2000)
• emp2 = Employee("Manni", 5000)
• print ("Employee.__doc__:", Employee.__doc__)
• print ("Employee.__module__:", Employee.__module__)
• print ("Employee.__bases__:", Employee.__bases__)
• print ("Employee.__dict__:", Employee.__dict__ )
Class Inheritance
• Instead of starting from a scratch, you can create a class by deriving
it from a pre-existing class by listing the parent class in parentheses
after the new class name.
• The child class inherits the attributes of its parent class, and you can
use those attributes as if they were defined in the child class. A
child class can also override data members and methods from the
parent.
• Syntax
• Derived classes are declared much like their parent class; however,
a list of base classes to inherit from is given after the class name −
• class SubClassName (ParentClass1, ParentClass2, ...):
• 'Optional class documentation string'
• class_suite
Type of inheritance
• Single Inheritance – where a derived class
acquires the members of a single super class.
• Multi-level inheritance – a derived class d1 is
inherited from base class base1, and d2 are
inherited from base2.
• Hierarchical inheritance – from one base class
you can inherit any number of child classes
• Multiple inheritance – a derived class is
inherited from more than one base class.
• You can use issubclass() or isinstance() functions
to check a relationships of two classes and
instances.
• The issubclass(sub, sup) boolean function returns
True, if the given subclass sub is indeed a subclass
of the superclass sup.
• The isinstance(obj, Class) boolean function
returns True, if obj is an instance of class Class or
is an instance of a subclass of Class
• Overriding Methods
• You can always override your parent class
methods. One reason for overriding parent's
methods is that you may want special or
different functionality in your subclass.
• class Parent: # define parent class def
• myMethod(self):
• print ('Calling parent method')
• class Child(Parent): # define child class def
• myMethod(self):
• print ('Calling child method')
• c = Child() # instance of child
• c.myMethod() # child calls overridden method
Method Overloading
• In Python you can define a method in such a
way that there are multiple ways to call it.
• Given a single method or function, we can
specify the number of parameters ourself.
• Depending on the function definition, it can
be called with zero, one, two or more
parameters.
Method Overloading
• class Human:
• def sayHello(self, name=None):
• if name is not None:
• print 'Hello ' + name
• else: print 'Hello ' # Create instance
obj = Human() # Call the method
obj.sayHello() # Call the method with a
parameter obj.sayHello('Guido')
Overloading Operators
• Suppose you have created a Vector class to
represent two-dimensional vectors. What
happens when you use the plus operator to
add them? Most likely Python will yell at you.
Operator Overloading Example
• class Vector:
• def __init__(self, a, b):
• self.a = a self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)
.
• class JustCounter:
• __secretCount = 0
• def count(self):
• self.__secretCount += 1
• print (self.__secretCount)
• counter = JustCounter()
• counter.count()
• counter.count()
• print (counter.__secretCount)
Inheritence
• One of the major advantages of Object
Oriented Programming is re-use. Inheritance is
one of the mechanisms to achieve the same.
In inheritance, a class (usually called
superclass) is inherited by another class
(usually called subclass). The subclass adds
some attributes to superclass.
• class Person(object):
•
• # Constructor
• def __init__(self, name):
• self.name = name
•
• # To get name
• def getName(self):
• return self.name
•
• # To check if this person is employee
• def isEmployee(self):
• return False
•
•
• # Inherited or Sub class (Note Person in bracket)
• class Employee(Person):
•
• # Here we return true
• def isEmployee(self):
• return True
•
• # Driver code
• emp = Person("Geek1") # An Object of Person
• print(emp.getName(), emp.isEmployee())
•
• emp = Employee("Geek2") # An Object of Employee
• print(emp.getName(), emp.isEmployee())
Encapsulation
• The terms encapsulation and abstraction (also data hiding)
are often used as synonyms. They are nearly synonymous,
i.e. abstraction is achieved though encapsulation. Data
hiding and encapsulation are the same concept, so it's
correct to use them as synonyms.
• Generally speaking encapsulation is the mechanism for
restricting the access to some of an object's components,
this means that the internal representation of an object
can't be seen from outside of the objects definition. Access
to this data is typically only achieved through special
methods: Getters and Setters. By using solely get() and set()
methods, we can make sure that the internal data cannot
be accidentally set into an inconsistent or invalid state.
Polymorphism
• class Bear(object):
• def sound(self):
• print "Groarrr"
• class Dog(object):
• def sound(self):
• print "Woof woof!"
• def makeSound(animalType):
• animalType.sound()
• bearObj = Bear()
• dogObj = Dog()
• makeSound(bearObj)
• makeSound(dogObj)
• class Document:
• name=“”
• def __init__(self, name):
• self.name = name
• def show(self):
• return ("Subclass must implement abstract method")
• class Pdf(Document):
• def show(self):
• return 'Show pdf contents!'
• class Word(Document):
• def show(self):
• return 'Show word contents!'
• documents = [Pdf('Document1'), Pdf('Document2'), Word('Document3'),Document(“xyz”)]
• for k in documents:
• print k.name + ': ' + k.show()
• Generators:
• Python generators are a simple way of
creating iterators. All the overhead we
mentioned above are automatically handled
by generators in Python.
• Simply speaking, a generator is a function that
returns an object (iterator) which we can
iterate over (one value at a time).
• How to create a generator in Python?
• It is fairly simple to create a generator in Python. It is as
easy as defining a normal function with yield statement
instead of a return statement.
• If a function contains at least one yield statement (it may
contain other yield or returnstatements), it becomes a
generator function. Both yield and return will return some
value from a function.
• The difference is that, while a return statement terminates
a function entirely, yieldstatement pauses the function
saving all its states and later continues from there on
successive calls.
• Differences between Generator function and a Normal function
• Here is how a generator function differs from a normal function.
• Generator function contains one or more yield statement.
• When called, it returns an object (iterator) but does not start
execution immediately.
• Methods like __iter__() and __next__() are implemented
automatically. So we can iterate through the items using next().
• Once the function yields, the function is paused and the control is
transferred to the caller.
• Local variables and their states are remembered between
successive calls.
• Finally, when the function terminates, StopIteration is raised
automatically on further calls.
• Python Generators with a Loop
• The above example is of less use and we
studied it just to get an idea of what was
happening in the background.
• Normally, generator functions are
implemented with a loop having a suitable
terminating condition.
• Python Generator Expression
• Simple generators can be easily created on the fly using generator
expressions. It makes building generators easy.
• Same as lambda function creates an anonymous function, generator
expression creates an anonymous generator function.
• The syntax for generator expression is similar to that of a list
comprehension in Python. But the square brackets are replaced with
round parentheses.
• The major difference between a list comprehension and a generator
expression is that while list comprehension produces the entire list,
generator expression produces one item at a time.
• They are kind of lazy, producing items only when asked for. For this reason,
a generator expression is much more memory efficient than an equivalent
list comprehension.
•
• Why generators are used in Python?
• There are several reasons which make generators an
attractive implementation to go for.
• 1. Easy to Implement
• Generators can be implemented in a clear and concise
way as compared to their iterator class counterpart.
Following is an example to implement a sequence of
power of 2's using iterator class.
• Since, generators keep track of details automatically, it
was concise and much cleaner in implementation.
• 2. Memory Efficient
• A normal function to return a sequence will
create the entire sequence in memory before
returning the result. This is an overkill if the
number of items in the sequence is very large.
• Generator implementation of such sequence
is memory friendly and is preferred since it
only produces one item at a time.
• 3. Represent Infinite Stream
• Generators are excellent medium to represent an infinite stream of data. Infinite
streams cannot be stored in memory and since generators produce only one item
at a time, it can represent infinite stream of data.
• The following example can generate all the even numbers (at least in theory).
• def all_even(): n = 0 while True: yield n n += 24. Pipelining Generators
• Generators can be used to pipeline a series of operations. This is best illustrated
using an example.
• Suppose we have a log file from a famous fast food chain. The log file has a column
(4th column) that keeps track of the number of pizza sold every hour and we want
to sum it to find the total pizzas sold in 5 years.
• Assume everything is in string and numbers that are not available are marked as
'N/A'. A generator implementation of this could be as follows.
• with open('sells.log') as file: pizza_col = (line[3] for line in file) per_hour = (int(x)
for x in pizza_col if x != 'N/A') print("Total pizzas sold = ",sum(per_hour))This
pipelining is efficient and easy to read (and yes, a lot cooler!).
Tkinter
Tk was developed as a GUI extension for the Tcl scripting language by John
Ousterhout. The first release was in 1991. Tk proved as extremely successful in
the 1990's, because it is easier to learn and to use than other toolkits. So it is no
wonder that many programmers wanted to use Tk independently of Tcl. That's
why bindings for lots of other programming languages have been developed,
including Perl, Ada (called TASH), Python (called Tkinter), Ruby, and Common
Lisp.
• Simple frame:
• import tkinter
• top = tkinter.Tk()
• # Code to add widgets will go here... top.
• mainloop()
Tkinter Widgets
• Sr.No.Operator & Description
• 1ButtonThe Button widget is used to display buttons in your application.
• 3CheckbuttonThe Checkbutton widget is used to display a number of
options as checkboxes. The user can select multiple options at a time.
• 4EntryThe Entry widget is used to display a single-line text field for
accepting values from a user.
• 5FrameThe Frame widget is used as a container widget to organize other
widgets.
• 6LabelThe Label widget is used to provide a single-line caption for other
widgets. It can also contain images.
• 7ListboxThe Listbox widget is used to provide a list of options to a user.
• 8MenubuttonThe Menubutton widget is used to display menus in your
application.
• 9MenuThe Menu widget is used to provide various commands to a user.
These commands are contained inside Menubutton.
• 10MessageThe Message widget is used to display multiline text fields for
accepting values from a user.
• 11RadiobuttonThe Radiobutton widget is used to display a number of
options as radio buttons. The user can select only one option at a time.
• 12ScaleThe Scale widget is used to provide a slider widget.
• 13ScrollbarThe Scrollbar widget is used to add scrolling capability to
various widgets, such as list boxes.
• 14TextThe Text widget is used to display text in multiple lines.
• 15ToplevelThe Toplevel widget is used to provide a separate window
container.
• 16SpinboxThe Spinbox widget is a variant of the standard Tkinter Entry
widget, which can be used to select from a fixed number of values.
• 17PanedWindowA PanedWindow is a container widget that may contain
any number of panes, arranged horizontally or vertically.
• 18LabelFrameA labelframe is a simple container widget. Its primary
purpose is to act as a spacer or container for complex window layouts.
• 19MessageBoxThis module is used to display message boxes in your
applications.
Standard attributes
• Dimensionsactivebackground What background color to use when the button is active. The
default is system specific. (the option database name is
activeBackground, the class is Foreground)
activeforeground What foreground color to use when the button is active. The
default is system specific. (activeForeground/Background)
anchor Controls where in the button the text (or image) should be
located. Use one of N, NE, E, SE, S, SW, W, NW, orCENTER.
Default is CENTER. (anchor/Anchor)
background The background color. The default is system specific.
(background/Background)
bg Same as background
cursor The cursor to show when the mouse is moved over the
button. (cursor/Cursor)
bitmap The bitmap to display in the widget. If the image option is
given, this option is ignored. (bitmap/Bitmap)
command A function or method that is called when the button is pressed. The
callback can be a function, bound method, or any other callable
Python object. If this option is not used, nothing will happen when
the user presses the button. (command/Command)
compound Controls how to combine text and image in the button. By default, if
an image or bitmap is given, it is drawn instead of the text. If this
option is set to CENTER, the text is drawn on top of the image. If this
option is set to one of BOTTOM, LEFT, RIGHT, or TOP, the image is
drawn besides the text (use BOTTOM to draw the image under the
text, etc.). Default is NONE. (compound/Compound)
default If set, the button is a default button. Tkinter will indicate this by
drawing a platform specific indicator (usually an extra border). The
default is DISABLED (no default behavior). (default/Default)
Disabled
foreground
The color to use when the button is disabled. The background is
shown in the background color. The default is system specific.
(disabledForeground/DisabledForeground)
font The font to use in the button. The button can only contain text in a
single font. The default is system specific. (font/Font)
foreground The color to use for text and bitmap content. The default is system
specific. (foreground/Foreground)
fg Same as foreground
height The height of the button. If the button displays text, the size is
given in text units. If the button displays an image, the size is
given in pixels (or screen units). If the size is omitted, it is
calculated based on the button contents. (height/Height)
highlightbackgrou
nd
The color to use for the highlight border when the button does
not have focus. The default is system specific.
(highlightBackground/HighlightBackground)
highlightcolor The color to use for the highlight border when the button has
focus. The default is system speciific.
(highlightColor/HighlightColor)
highlightthickness The width of the highlight border. The default is system specific
(usually one or two pixels).
(highlightThickness/HighlightThickness)
Image The image to display in the widget. If specified, this takes
precedence over the text and bitmap options. (image/Image)
justify Defines how to align multiple lines of text. Use LEFT, RIGHT,
or CENTER. Default is CENTER. (justify/Justify)
overrelief Alternative relief to use when the mouse is moved over the
widget. If empty, always use the relief value.
(overRelief/OverRelief)
padx Extra horizontal padding between the text or image and the
border
pady Extra vertical padding between the text or image and the border.
(padY/Pad)
relief Border decoration. Usually, the button is SUNKEN when pressed,
and RAISED otherwise. Other possible values are GROOVE, RIDGE,
and FLAT. Default is RAISED. (relief/Relief)
repeatdelay (repeatDelay/RepeatDelay)
repeatinterval (repeatInterval/RepeatInterval)
state The button state: NORMAL, ACTIVE or DISABLED. Default
is NORMAL
takefocus Indicates that the user can use the Tab key to move to this button.
Default is an empty string, which means that the button accepts
focus only if it has any keyboard bindings (default is on, in other
words). (takeFocus/TakeFocus)
text The text to display in the button. The text can contain newlines. If
the bitmap or image options are used, this option is ignored (unless
the compound option is used). (text/Text)
textvariable Associates a Tkinter variable (usually a StringVar) to the button. If the
variable is changed, the button text is updated. (textVariable/Variable)
underline Which character to underline, in a text label. Default is -1, which
means that no character is underlined. (underline/Underline)
width The width of the button. If the button displays text, the size is given in
text units. If the button displays an image, the size is given in pixels (or
screen units). If the size is omitted, or zero, it is calculated based on
the button contents. (width/Width)
wraplength Determines when a button’s text should be wrapped into multiple
lines. This is given in screen units. Default is 0 (no wrapping).
(wrapLength/WrapLength)
• Geometry Management
• All Tkinter widgets have access to specific geometry management
methods, which have the purpose of organizing widgets throughout
the parent widget area. Tkinter expose
• s the following geometry manager classes: pack, grid, and place.
• The pack() Method − This geometry manager organizes widgets in
blocks before placing them in the parent widget.
• The grid() Method − This geometry manager organizes widgets in a
table-like structure in the parent widget.
• The place() Method − This geometry manager organizes widgets by
placing them in a specific position in the parent widget.
<Button> A mouse button is pressed with the mouse pointer over the widget. The
detail part specifies which button, e.g. The left mouse button is defined
by the event <Button-1>, the middle button by <Button-2>, and the
rightmost mouse button by <Button-3>.
<Button-4> defines the scroll up event on mice with wheel support and
and <Button-5> the scroll down.
If you press down a mouse button over a widget and keep it pressed,
Tkinter will automatically "grab" the mouse pointer. Further mouse
events like Motion and Release events will be sent to the current
widget, even if the mouse is moved outside the current widget. The
current position, relative to the widget, of the mouse pointer is
provided in the x and y members of the event object passed to the
callback. You can use ButtonPress instead of Button, or even leave it out
completely: , , and <1> are all synonyms.
<Motion> The mouse is moved with a mouse button being held down. To specify
the left, middle or right mouse button use <B1-Motion>, <B2-Motion>
and <B3-Motion> respectively. The current position of the mouse pointer
is provided in the x and y members of the event object passed to the
callback, i.e. event.x, event.y
<Double-
Button>
Similar to the Button event, see above, but the button is double clicked
instead of a single click. To specify the left, middle or right mouse button
use <Double-Button-1>, <Double-Button-2>, and <Double-Button-3>
respectively.
You can use Double or Triple as prefixes. Note that if you bind to both a
single click (<Button-1>) and a double click (<Double-Button-1>), both
bindings will be called.
<ButtonRel
ease>
Event, if a button is released. To specify the left, middle or right mouse
button use <ButtonRelease-1>, <ButtonRelease-2>, and <ButtonRelease-
3> respectively. The current position of the mouse pointer is provided in
the x and y members of the event object passed to the callback, i.e.
event.x, event.y
<Enter> The mouse pointer entered the widget.
Attention: This doesn't mean that the user pressed the Enter key!.
<Return> is used for this purpose.
<Leave> The mouse pointer left the widget.
<FocusOu
t>
Keyboard focus was moved from this widget to another widget.
<FocusIn> Keyboard focus was moved to this widget, or to a child of this widget.
<Return> The user pressed the Enter key. You can bind to virtually all keys on the
keyboard: The special keys are Cancel (the Break key), BackSpace, Tab,
Return(the Enter key), Shift_L (any Shift key), Control_L (any Control key),
Alt_L (any Alt key), Pause, Caps_Lock, Escape, Prior (Page Up), Next (Page
Down), End, Home, Left, Up, Right, Down, Print, Insert, Delete, F1, F2, F3,
F4, F5, F6, F7, F8, F9, F10, F11, F12, Num_Lock, and Scroll_Lock.
<Key> The user pressed any key. The key is provided in the char member of the
event object passed to the callback (this is an empty string for special
keys).
a The user typed an "a" key. Most printable characters can be used as is.
The exceptions are space (<space>) and less than (<less>). Note that 1 is
a keyboard binding, while <1> is a button binding.
<Shift-Up> The user pressed the Up arrow, while holding the Shift key pressed. You
can use prefixes like Alt, Shift, and Control.
<Configure> The size of the widget changed. The new size is provided in the width
and height attributes of the event object passed to the callback. On
some platforms, it can mean that the location changed.
Threding
• Running several threads is similar to running several different programs
concurrently, but with the following benefits −
• Multiple threads within a process share the same data space with the
main thread and can therefore share information or communicate with
each other more easily than if they were separate processes.
• Threads are sometimes called light-weight processes and they do not
require much memory overhead; they are cheaper than processes.
• A thread has a beginning, an execution sequence, and a conclusion. It has
an instruction pointer that keeps track of where within its context is it
currently running.
• It can be pre-empted (interrupted).
• It can temporarily be put on hold (also known as sleeping) while other
threads are running - this is called yielding.
• There are two different kind of threads −
• kernel thread
• user thread
• Kernel Threads are a part of the operating system, while
the User-space threads are not implemented in the kernel.
• There are two modules which support the usage of threads
in Python3 −
• _thread
• threading
• The thread module has been "deprecated" for quite a long
time. Users are encouraged to use the threading module
instead. Hence, in Python 3, the module "thread" is not
available anymore. However, it has been renamed to
"_thread" for backwards compatibilities in Python3

More Related Content

What's hot

09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
Denis Ristic
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
yugandhar vadlamudi
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
Jalpesh Vasa
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
Aleksander Fabijan
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPWildan Maulana
 
PHP- Introduction to Object Oriented PHP
PHP-  Introduction to Object Oriented PHPPHP-  Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented PHP
Vibrant Technologies & Computers
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
Raghunath A
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpMichael Girouard
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Advanced php
Advanced phpAdvanced php
Advanced phphamfu
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
wahidullah mudaser
 

What's hot (20)

09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
 
PHP- Introduction to Object Oriented PHP
PHP-  Introduction to Object Oriented PHPPHP-  Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented PHP
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
 
A Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented PhpA Gentle Introduction To Object Oriented Php
A Gentle Introduction To Object Oriented Php
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Advanced php
Advanced phpAdvanced php
Advanced php
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 

Similar to Python advance

object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)
Jyoti shukla
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
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
Maulik Borsaniya
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
DrDhivyaaCRAssistant
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
Synapseindiappsdevelopment
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
Workhorse Computing
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
Jalpesh Vasa
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
C#2
C#2C#2
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
ilias ahmed
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
ShaownRoy1
 

Similar to Python advance (20)

Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
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
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
Python session 7 by Shan
Python session 7 by ShanPython session 7 by Shan
Python session 7 by Shan
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
Pythonclass
PythonclassPythonclass
Pythonclass
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
C#2
C#2C#2
C#2
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 

Recently uploaded

Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
drwaing
 
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.pptPROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
bhadouriyakaku
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
ssuser36d3051
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
Mukeshwaran Balu
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
Divyam548318
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
Fundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptxFundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptx
manasideore6
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
awadeshbabu
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 

Recently uploaded (20)

Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
 
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.pptPROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
PROJECT FORMAT FOR EVS AMITY UNIVERSITY GWALIOR.ppt
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
sieving analysis and results interpretation
sieving analysis and results interpretationsieving analysis and results interpretation
sieving analysis and results interpretation
 
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
ACRP 4-09 Risk Assessment Method to Support Modification of Airfield Separat...
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
Fundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptxFundamentals of Induction Motor Drives.pptx
Fundamentals of Induction Motor Drives.pptx
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 

Python advance

  • 2. • Class • Exception handling • Generators • CGI • Databases • Tkinter(GUI) • Regular expression • Email sending(SMTP)
  • 3. Object-oriented language • Python is a multi-paradigm programming language. Meaning, it supports different programming approach. • One of the popular approach to solve a programming problem is by creating objects. This is known as Object-Oriented Programming (OOP). • An object has two characteristics: • attributes • Behavior • The concept of OOP in Python focuses on creating reusable code. This concept is also known as DRY (Don't Repeat Yourself). • In Python, the concept of OOP follows some basic principles: • Inheritance-A process of using details from a new class without modifying existing class. • Encapsulation-Hiding the private details of a class from other objects. • Polymorphism-A concept of using common operation in different ways for different data input.
  • 4. Object-oriented language • Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation. • Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are. • Data member − A class variable or instance variable that holds data associated with a class and its objects. • Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.
  • 5. • Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class. • Inheritance − The transfer of the characteristics of a class to other classes that are derived from it. • Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle. • Instantiation − The creation of an instance of a class. • Method − A special kind of function that is defined in a class definition. • Object − A unique instance of a data structure that is defined by its class. An object comprises both data members (class variables and instance variables) and methods. • Operator overloading − The assignment of more than one function to a particular operator.
  • 6. • In Python, the concept of OOP follows some basic principles: • Inheritance-A process of using details from a new class without modifying existing class. • Abstraction-Hiding the private details of a class from other objects. • Polymorphism-A concept of using common operation in different ways for different data input.
  • 7. • Name Notation Behaviour name Public Can be accessed from inside • and outside _name Protected Like a public member, • but they shouldn't be • directly accessed from • outside. __name Private Can't be seen and accessed • from outsid’
  • 8. Creating Classes • The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows − • class ClassName: • class body • which can be accessed via ClassName.__doc__. • The class_suite consists of all the component statements defining class members, data attributes and functions.
  • 9. • Ex. • class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print ("Total Employee %d" % Employee.empCount) def displayEmployee(self): print ("Name : ", self.name, ", Salary: ", self.salary)
  • 10. Creating Instance Objects • Creating Instance Objects • class emp1 = Employee("Zara", 2000) • emp2 = Employee("Manni", 5000) • Accessing Attributes • emp1.displayEmployee() emp2.displayEmployee() • print ("Total Employee”,Employee.empCount)
  • 11. • Ex. • class Employee: • 'Common base class for all employees' empCount = 0 • def __init__(self, name, salary): • self.name = name • self.salary = salary • Employee.empCount += 1 • def displayCount(self): • print ("Total Employee %d" % Employee.empCount) • def displayEmployee(self): • print ("Name : ", self.name, ", Salary: ", self.salary) • #This would create first object of Employee class" • emp1 = Employee("Zara", 2000) • #This would create second object of Employee class“ • emp2 = Employee("Manni", 5000) • emp1.displayEmployee() • emp2.displayEmployee() • print ("Total Employee %d" % Employee.empCount)
  • 12. Access Attribute • access attributes • The getattr(obj, name[, default]) − to access the attribute of object. • The hasattr(obj,name) − to check if an attribute exists or not. • The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would be created. • The delattr(obj, name) − to delete an attribute.
  • 13. In Built Class Attribute • Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute − • __dict__ − Dictionary containing the class's namespace. • __doc__ − Class documentation string or none, if undefined. • __module__ − Module name in which the class is defined. This attribute is "__main__" in interactive mode. • __bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
  • 14. • class Employee: • 'Common base class for all employees' • empCount = 0 • def __init__(self, name, salary): • self.name = name • self.salary = salary • Employee.empCount += 1 • def displayCount(self): • print ("Total Employee %d" % Employee.empCount) • def displayEmployee(self): • print ("Name : ", self.name, ", Salary: ", self.salary) • emp1 = Employee("Zara", 2000) • emp2 = Employee("Manni", 5000) • print ("Employee.__doc__:", Employee.__doc__) • print ("Employee.__module__:", Employee.__module__) • print ("Employee.__bases__:", Employee.__bases__) • print ("Employee.__dict__:", Employee.__dict__ )
  • 15. Class Inheritance • Instead of starting from a scratch, you can create a class by deriving it from a pre-existing class by listing the parent class in parentheses after the new class name. • The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent. • Syntax • Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name − • class SubClassName (ParentClass1, ParentClass2, ...): • 'Optional class documentation string' • class_suite
  • 16. Type of inheritance • Single Inheritance – where a derived class acquires the members of a single super class. • Multi-level inheritance – a derived class d1 is inherited from base class base1, and d2 are inherited from base2. • Hierarchical inheritance – from one base class you can inherit any number of child classes • Multiple inheritance – a derived class is inherited from more than one base class.
  • 17. • You can use issubclass() or isinstance() functions to check a relationships of two classes and instances. • The issubclass(sub, sup) boolean function returns True, if the given subclass sub is indeed a subclass of the superclass sup. • The isinstance(obj, Class) boolean function returns True, if obj is an instance of class Class or is an instance of a subclass of Class
  • 18. • Overriding Methods • You can always override your parent class methods. One reason for overriding parent's methods is that you may want special or different functionality in your subclass.
  • 19. • class Parent: # define parent class def • myMethod(self): • print ('Calling parent method') • class Child(Parent): # define child class def • myMethod(self): • print ('Calling child method') • c = Child() # instance of child • c.myMethod() # child calls overridden method
  • 20. Method Overloading • In Python you can define a method in such a way that there are multiple ways to call it. • Given a single method or function, we can specify the number of parameters ourself. • Depending on the function definition, it can be called with zero, one, two or more parameters.
  • 21. Method Overloading • class Human: • def sayHello(self, name=None): • if name is not None: • print 'Hello ' + name • else: print 'Hello ' # Create instance obj = Human() # Call the method obj.sayHello() # Call the method with a parameter obj.sayHello('Guido')
  • 22. Overloading Operators • Suppose you have created a Vector class to represent two-dimensional vectors. What happens when you use the plus operator to add them? Most likely Python will yell at you.
  • 23. Operator Overloading Example • class Vector: • def __init__(self, a, b): • self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print (v1 + v2) .
  • 24. • class JustCounter: • __secretCount = 0 • def count(self): • self.__secretCount += 1 • print (self.__secretCount) • counter = JustCounter() • counter.count() • counter.count() • print (counter.__secretCount)
  • 25. Inheritence • One of the major advantages of Object Oriented Programming is re-use. Inheritance is one of the mechanisms to achieve the same. In inheritance, a class (usually called superclass) is inherited by another class (usually called subclass). The subclass adds some attributes to superclass.
  • 26. • class Person(object): • • # Constructor • def __init__(self, name): • self.name = name • • # To get name • def getName(self): • return self.name • • # To check if this person is employee • def isEmployee(self): • return False • • • # Inherited or Sub class (Note Person in bracket) • class Employee(Person): • • # Here we return true • def isEmployee(self): • return True • • # Driver code • emp = Person("Geek1") # An Object of Person • print(emp.getName(), emp.isEmployee()) • • emp = Employee("Geek2") # An Object of Employee • print(emp.getName(), emp.isEmployee())
  • 27. Encapsulation • The terms encapsulation and abstraction (also data hiding) are often used as synonyms. They are nearly synonymous, i.e. abstraction is achieved though encapsulation. Data hiding and encapsulation are the same concept, so it's correct to use them as synonyms. • Generally speaking encapsulation is the mechanism for restricting the access to some of an object's components, this means that the internal representation of an object can't be seen from outside of the objects definition. Access to this data is typically only achieved through special methods: Getters and Setters. By using solely get() and set() methods, we can make sure that the internal data cannot be accidentally set into an inconsistent or invalid state.
  • 28. Polymorphism • class Bear(object): • def sound(self): • print "Groarrr" • class Dog(object): • def sound(self): • print "Woof woof!" • def makeSound(animalType): • animalType.sound() • bearObj = Bear() • dogObj = Dog() • makeSound(bearObj) • makeSound(dogObj)
  • 29. • class Document: • name=“” • def __init__(self, name): • self.name = name • def show(self): • return ("Subclass must implement abstract method") • class Pdf(Document): • def show(self): • return 'Show pdf contents!' • class Word(Document): • def show(self): • return 'Show word contents!' • documents = [Pdf('Document1'), Pdf('Document2'), Word('Document3'),Document(“xyz”)] • for k in documents: • print k.name + ': ' + k.show()
  • 30. • Generators: • Python generators are a simple way of creating iterators. All the overhead we mentioned above are automatically handled by generators in Python. • Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).
  • 31. • How to create a generator in Python? • It is fairly simple to create a generator in Python. It is as easy as defining a normal function with yield statement instead of a return statement. • If a function contains at least one yield statement (it may contain other yield or returnstatements), it becomes a generator function. Both yield and return will return some value from a function. • The difference is that, while a return statement terminates a function entirely, yieldstatement pauses the function saving all its states and later continues from there on successive calls.
  • 32. • Differences between Generator function and a Normal function • Here is how a generator function differs from a normal function. • Generator function contains one or more yield statement. • When called, it returns an object (iterator) but does not start execution immediately. • Methods like __iter__() and __next__() are implemented automatically. So we can iterate through the items using next(). • Once the function yields, the function is paused and the control is transferred to the caller. • Local variables and their states are remembered between successive calls. • Finally, when the function terminates, StopIteration is raised automatically on further calls.
  • 33. • Python Generators with a Loop • The above example is of less use and we studied it just to get an idea of what was happening in the background. • Normally, generator functions are implemented with a loop having a suitable terminating condition.
  • 34. • Python Generator Expression • Simple generators can be easily created on the fly using generator expressions. It makes building generators easy. • Same as lambda function creates an anonymous function, generator expression creates an anonymous generator function. • The syntax for generator expression is similar to that of a list comprehension in Python. But the square brackets are replaced with round parentheses. • The major difference between a list comprehension and a generator expression is that while list comprehension produces the entire list, generator expression produces one item at a time. • They are kind of lazy, producing items only when asked for. For this reason, a generator expression is much more memory efficient than an equivalent list comprehension. •
  • 35. • Why generators are used in Python? • There are several reasons which make generators an attractive implementation to go for. • 1. Easy to Implement • Generators can be implemented in a clear and concise way as compared to their iterator class counterpart. Following is an example to implement a sequence of power of 2's using iterator class. • Since, generators keep track of details automatically, it was concise and much cleaner in implementation.
  • 36. • 2. Memory Efficient • A normal function to return a sequence will create the entire sequence in memory before returning the result. This is an overkill if the number of items in the sequence is very large. • Generator implementation of such sequence is memory friendly and is preferred since it only produces one item at a time.
  • 37. • 3. Represent Infinite Stream • Generators are excellent medium to represent an infinite stream of data. Infinite streams cannot be stored in memory and since generators produce only one item at a time, it can represent infinite stream of data. • The following example can generate all the even numbers (at least in theory). • def all_even(): n = 0 while True: yield n n += 24. Pipelining Generators • Generators can be used to pipeline a series of operations. This is best illustrated using an example. • Suppose we have a log file from a famous fast food chain. The log file has a column (4th column) that keeps track of the number of pizza sold every hour and we want to sum it to find the total pizzas sold in 5 years. • Assume everything is in string and numbers that are not available are marked as 'N/A'. A generator implementation of this could be as follows. • with open('sells.log') as file: pizza_col = (line[3] for line in file) per_hour = (int(x) for x in pizza_col if x != 'N/A') print("Total pizzas sold = ",sum(per_hour))This pipelining is efficient and easy to read (and yes, a lot cooler!).
  • 38.
  • 39. Tkinter Tk was developed as a GUI extension for the Tcl scripting language by John Ousterhout. The first release was in 1991. Tk proved as extremely successful in the 1990's, because it is easier to learn and to use than other toolkits. So it is no wonder that many programmers wanted to use Tk independently of Tcl. That's why bindings for lots of other programming languages have been developed, including Perl, Ada (called TASH), Python (called Tkinter), Ruby, and Common Lisp.
  • 40. • Simple frame: • import tkinter • top = tkinter.Tk() • # Code to add widgets will go here... top. • mainloop()
  • 41. Tkinter Widgets • Sr.No.Operator & Description • 1ButtonThe Button widget is used to display buttons in your application. • 3CheckbuttonThe Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time. • 4EntryThe Entry widget is used to display a single-line text field for accepting values from a user. • 5FrameThe Frame widget is used as a container widget to organize other widgets. • 6LabelThe Label widget is used to provide a single-line caption for other widgets. It can also contain images. • 7ListboxThe Listbox widget is used to provide a list of options to a user. • 8MenubuttonThe Menubutton widget is used to display menus in your application. • 9MenuThe Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton. • 10MessageThe Message widget is used to display multiline text fields for accepting values from a user.
  • 42. • 11RadiobuttonThe Radiobutton widget is used to display a number of options as radio buttons. The user can select only one option at a time. • 12ScaleThe Scale widget is used to provide a slider widget. • 13ScrollbarThe Scrollbar widget is used to add scrolling capability to various widgets, such as list boxes. • 14TextThe Text widget is used to display text in multiple lines. • 15ToplevelThe Toplevel widget is used to provide a separate window container. • 16SpinboxThe Spinbox widget is a variant of the standard Tkinter Entry widget, which can be used to select from a fixed number of values. • 17PanedWindowA PanedWindow is a container widget that may contain any number of panes, arranged horizontally or vertically. • 18LabelFrameA labelframe is a simple container widget. Its primary purpose is to act as a spacer or container for complex window layouts. • 19MessageBoxThis module is used to display message boxes in your applications.
  • 43. Standard attributes • Dimensionsactivebackground What background color to use when the button is active. The default is system specific. (the option database name is activeBackground, the class is Foreground) activeforeground What foreground color to use when the button is active. The default is system specific. (activeForeground/Background) anchor Controls where in the button the text (or image) should be located. Use one of N, NE, E, SE, S, SW, W, NW, orCENTER. Default is CENTER. (anchor/Anchor) background The background color. The default is system specific. (background/Background) bg Same as background cursor The cursor to show when the mouse is moved over the button. (cursor/Cursor) bitmap The bitmap to display in the widget. If the image option is given, this option is ignored. (bitmap/Bitmap)
  • 44. command A function or method that is called when the button is pressed. The callback can be a function, bound method, or any other callable Python object. If this option is not used, nothing will happen when the user presses the button. (command/Command) compound Controls how to combine text and image in the button. By default, if an image or bitmap is given, it is drawn instead of the text. If this option is set to CENTER, the text is drawn on top of the image. If this option is set to one of BOTTOM, LEFT, RIGHT, or TOP, the image is drawn besides the text (use BOTTOM to draw the image under the text, etc.). Default is NONE. (compound/Compound) default If set, the button is a default button. Tkinter will indicate this by drawing a platform specific indicator (usually an extra border). The default is DISABLED (no default behavior). (default/Default) Disabled foreground The color to use when the button is disabled. The background is shown in the background color. The default is system specific. (disabledForeground/DisabledForeground) font The font to use in the button. The button can only contain text in a single font. The default is system specific. (font/Font) foreground The color to use for text and bitmap content. The default is system specific. (foreground/Foreground) fg Same as foreground
  • 45. height The height of the button. If the button displays text, the size is given in text units. If the button displays an image, the size is given in pixels (or screen units). If the size is omitted, it is calculated based on the button contents. (height/Height) highlightbackgrou nd The color to use for the highlight border when the button does not have focus. The default is system specific. (highlightBackground/HighlightBackground) highlightcolor The color to use for the highlight border when the button has focus. The default is system speciific. (highlightColor/HighlightColor) highlightthickness The width of the highlight border. The default is system specific (usually one or two pixels). (highlightThickness/HighlightThickness) Image The image to display in the widget. If specified, this takes precedence over the text and bitmap options. (image/Image) justify Defines how to align multiple lines of text. Use LEFT, RIGHT, or CENTER. Default is CENTER. (justify/Justify) overrelief Alternative relief to use when the mouse is moved over the widget. If empty, always use the relief value. (overRelief/OverRelief)
  • 46. padx Extra horizontal padding between the text or image and the border pady Extra vertical padding between the text or image and the border. (padY/Pad) relief Border decoration. Usually, the button is SUNKEN when pressed, and RAISED otherwise. Other possible values are GROOVE, RIDGE, and FLAT. Default is RAISED. (relief/Relief) repeatdelay (repeatDelay/RepeatDelay) repeatinterval (repeatInterval/RepeatInterval) state The button state: NORMAL, ACTIVE or DISABLED. Default is NORMAL takefocus Indicates that the user can use the Tab key to move to this button. Default is an empty string, which means that the button accepts focus only if it has any keyboard bindings (default is on, in other words). (takeFocus/TakeFocus)
  • 47. text The text to display in the button. The text can contain newlines. If the bitmap or image options are used, this option is ignored (unless the compound option is used). (text/Text) textvariable Associates a Tkinter variable (usually a StringVar) to the button. If the variable is changed, the button text is updated. (textVariable/Variable) underline Which character to underline, in a text label. Default is -1, which means that no character is underlined. (underline/Underline) width The width of the button. If the button displays text, the size is given in text units. If the button displays an image, the size is given in pixels (or screen units). If the size is omitted, or zero, it is calculated based on the button contents. (width/Width) wraplength Determines when a button’s text should be wrapped into multiple lines. This is given in screen units. Default is 0 (no wrapping). (wrapLength/WrapLength)
  • 48. • Geometry Management • All Tkinter widgets have access to specific geometry management methods, which have the purpose of organizing widgets throughout the parent widget area. Tkinter expose • s the following geometry manager classes: pack, grid, and place. • The pack() Method − This geometry manager organizes widgets in blocks before placing them in the parent widget. • The grid() Method − This geometry manager organizes widgets in a table-like structure in the parent widget. • The place() Method − This geometry manager organizes widgets by placing them in a specific position in the parent widget.
  • 49. <Button> A mouse button is pressed with the mouse pointer over the widget. The detail part specifies which button, e.g. The left mouse button is defined by the event <Button-1>, the middle button by <Button-2>, and the rightmost mouse button by <Button-3>. <Button-4> defines the scroll up event on mice with wheel support and and <Button-5> the scroll down. If you press down a mouse button over a widget and keep it pressed, Tkinter will automatically "grab" the mouse pointer. Further mouse events like Motion and Release events will be sent to the current widget, even if the mouse is moved outside the current widget. The current position, relative to the widget, of the mouse pointer is provided in the x and y members of the event object passed to the callback. You can use ButtonPress instead of Button, or even leave it out completely: , , and <1> are all synonyms.
  • 50. <Motion> The mouse is moved with a mouse button being held down. To specify the left, middle or right mouse button use <B1-Motion>, <B2-Motion> and <B3-Motion> respectively. The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback, i.e. event.x, event.y <Double- Button> Similar to the Button event, see above, but the button is double clicked instead of a single click. To specify the left, middle or right mouse button use <Double-Button-1>, <Double-Button-2>, and <Double-Button-3> respectively. You can use Double or Triple as prefixes. Note that if you bind to both a single click (<Button-1>) and a double click (<Double-Button-1>), both bindings will be called. <ButtonRel ease> Event, if a button is released. To specify the left, middle or right mouse button use <ButtonRelease-1>, <ButtonRelease-2>, and <ButtonRelease- 3> respectively. The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback, i.e. event.x, event.y
  • 51. <Enter> The mouse pointer entered the widget. Attention: This doesn't mean that the user pressed the Enter key!. <Return> is used for this purpose. <Leave> The mouse pointer left the widget. <FocusOu t> Keyboard focus was moved from this widget to another widget. <FocusIn> Keyboard focus was moved to this widget, or to a child of this widget. <Return> The user pressed the Enter key. You can bind to virtually all keys on the keyboard: The special keys are Cancel (the Break key), BackSpace, Tab, Return(the Enter key), Shift_L (any Shift key), Control_L (any Control key), Alt_L (any Alt key), Pause, Caps_Lock, Escape, Prior (Page Up), Next (Page Down), End, Home, Left, Up, Right, Down, Print, Insert, Delete, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Num_Lock, and Scroll_Lock.
  • 52. <Key> The user pressed any key. The key is provided in the char member of the event object passed to the callback (this is an empty string for special keys). a The user typed an "a" key. Most printable characters can be used as is. The exceptions are space (<space>) and less than (<less>). Note that 1 is a keyboard binding, while <1> is a button binding. <Shift-Up> The user pressed the Up arrow, while holding the Shift key pressed. You can use prefixes like Alt, Shift, and Control. <Configure> The size of the widget changed. The new size is provided in the width and height attributes of the event object passed to the callback. On some platforms, it can mean that the location changed.
  • 53. Threding • Running several threads is similar to running several different programs concurrently, but with the following benefits − • Multiple threads within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes. • Threads are sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes. • A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer that keeps track of where within its context is it currently running. • It can be pre-empted (interrupted). • It can temporarily be put on hold (also known as sleeping) while other threads are running - this is called yielding. • There are two different kind of threads − • kernel thread • user thread
  • 54. • Kernel Threads are a part of the operating system, while the User-space threads are not implemented in the kernel. • There are two modules which support the usage of threads in Python3 − • _thread • threading • The thread module has been "deprecated" for quite a long time. Users are encouraged to use the threading module instead. Hence, in Python 3, the module "thread" is not available anymore. However, it has been renamed to "_thread" for backwards compatibilities in Python3