Python Object

Python Object

Python is an object oriented programming language. So, its main focus is on objects unlike procedure oriented programming languages which mainly focuses on functions.

In object oriented programming language, object is simply a collection of data (variables) and methods (functions) that act on those data.
Python Class

A class is a blueprint for the object. Let’s understand it by an example:

Suppose a class is a prototype of a building. A building contains all the details about the floor, doors, windows, etc. we can make another buildings (as many as we want) based on these details. So building is a class and we can create many objects from a class.

An object is also called an instance of a class and the process of creating this object is known as instantiation.Python classes contain all the standard features of Object Oriented Programming. A python class is a mixture of class mechanism of C++ and Modula-3.
Define a class in Python

In Python, a class is defined by using a keyword class like a function definition begins with the keyword def.

Syntax of a class definition:
1.    class ClassName: 
2.         
3.        . 
4.        . 
5.        . 
6.         

A class creates a new local namespace to define its all attributes. These attributes may be data or functions.

See this example:
file Qptions Window Help Python 3.5.2
>>> class MyClass:
“This is ApkZube”
a=50
def func(self):
print(‘Hello ApkZube’)

output:
>>> MyClass.a
50
>>>

There are also some special attributes that begins with double underscore (__). For example: __doc__ attribute. It is used to fetch the docstring of that class. When we define a class, a new class object is created with the same class name. This new class object provides a facility to access the different attributes as well as to instantiate new objects of that class.

See this example:
file Qptions Window Help Python 3.5.2
>>> class MyClass:
“This is ApkZube”
a=50
def func(self):
print(‘Hello ApkZube’)

output:
>>> MyClass.a
50
>>>MyClass.__doc__
“This is ApkZube”
>>>MyClass.func

Create an Object in Python

We can create new object instances of the classes. The procedure to create an object is similar to a function call.
Let’s take an example to create a new instance object ob. We can access attributes of objects by using the object name prefix.

See this example:
>» ob = MyClass()
>>> MyClass.func

>>> ob.func
<bound method HyClass. func of
>>> ob.func() Hello ApkZube >>>

Here, attributes may be data or method. Method of an object is corresponding functions of that class. For example: MyClass.func is a function object and ob.func is a method object.

Python Object Class Example
class Student: 
   def __init__(self, rollno, name): 
      self.rollno = rollno 
      self.name = name 
   def displayStudent(self): 
      print “rollno : “, self.rollno,  “, name: “, self.name 
emp1 = Student(121, “Ajeet”) 
emp2 = Student(122, “Sonoo”) 
emp1.displayStudent() 
emp2.displayStudent() 

Output:
rollno :  121 , name:  Ajeet 
rollno :  122 , name:  Sonoo 

Python Constructors

Python Constructors

A constructor is a special type of method (function) which is used to initialize the instance members of the class. Constructor can be parameterized and non-parameterized as well. Constructor definition executes when we create object of the class. Constructors also verify that there are enough resources for the object to perform any start-up task.

Creating a Constructor
A constructor is a class function that begins with double underscore (_). The name of the constructor is always the same __init__().

While creating an object, a constructor can accept arguments if necessary. When we create a class without a constructor, Python automatically creates a default constructor that doesn’t do anything.

Every class must have a constructor, even if it simply relies on the default constructor.

Python Constructor Example
Let’s create a class named ComplexNumber, having two functions __init__() function to initialize the variable and getData() to display the number properly.

See this example:
>>> class ComplexNumber:
def __init__(self,r=0,i=1):
self.real=r;
self.imag=i;
def getDat(self):
print(“(0)+(1)j”.format(self.real,self.imag))

Output :
>>>c1= ComplexNumber(5,6)
>>>c1.getData()
5+6j
>>>

You can create a new attribute for an object and read it well at the time of defining the values. But you can’t create the attribute for already defined objects.

See this example:
>>> c1 = ComplexNumber(5,6)
>>> c1.getData()
5+6j
>>> c2 ComplexNumber(11)
>>> c2.attr = 12
>>> (c2.real, c2.imag, c2.attr)
(11, 0, 12)
>>> cl.attr
Traceback (most recent call last):
File “<pyshellt6”, line 1, in
cl.attr
AttributeError: CornplexNumber •
            object has no attribute ‘attr’
In Python, Constructors can be parameterized and non-parameterized as well. The parameterized constructors are used to set custom value for instance variables that can be used further in the application.

Let’s see an example, here, we are creating a non parameterized constructor.

Python Non Parameterized Constructor Example
class Student: 
    # Constructor – non parameterized 
    def __init__(self): 
        print(“This is non parametrized constructor”) 
    def show(self,name): 
        print(“Hello”,name) 
student = Student() 
student.show(“irfan”) 

Output:
This is non parametrized constructor
Hello irfan
Let’s see an example, here, we are creating a parameterized constructor.

Python Parameterized Constructor Example
class Student: 
    # Constructor – parameterized 
    def __init__(self, name): 
        print(“This is parametrized constructor”) 
        self.name = name 
    def show(self): 
        print(“Hello”,self.name
student = Student(“irfan”) 
student.show() 

Output:
This is parametrized constructor
Hello irfan

Python Inheritance

Python Inheritance

What is Inheritance
Inheritance is a feature of Object Oriented Programming. It is used to specify that one class will get most or all of its features from its parent class. It is a very powerful feature which facilitates users to create a new class with a few or more modification to an existing class. The new class is called child class or derived class and the main class from which it inherits the properties is called base class or parent class.

The child class or derived class inherits the features from the parent class, adding new features to it. It facilitates re-usability of code.

Image representation:

The following are the syntax to achieve inheritance. We can either pass parent class name or parent class name with module name as we did in the below example.

Python Inheritance Syntax
class DerivedClassName(BaseClassName): 
     
    . 
    . 
    . 
     

Python Inheritance Syntax 2
class DerivedClassName(modulename.BaseClassName): 
     
    . 
    . 
    . 
     

Parameter explanation
The name BaseClassName must be defined in a scope containing the derived class definition. We can also use other arbitrary expressions in place of a base class name. This is used when the base class is defined in another module.

Python Inheritance Example

Let’s see a simple python inheritance example where we are using two classes: Animal and Dog. Animal is the parent or base class and Dog is the child class.
Here, we are defining eat() method in Animal class and bark() method in Dog class. In this example, we are creating instance of Dog class and calling eat() and bark() methods by the instance of child class only. Since, parent properties and behaviors are inherited to child object automatically, we can call parent and child class methods by the child instance only.

class Animal: 
    def eat(self):
      print ‘Eating…’
class Dog(Animal):   
   def bark(self):
      print ‘Barking…’
d=Dog()
d.eat()
d.bark()

Output:
Eating… 
Barking… 

Python Multilevel Inheritance

Python Multilevel Inheritance

Multilevel inheritance is also possible in Python like other Object Oriented programming languages. We can inherit a derived class from another derived class, this process is known as multilevel inheritance. In Python, multilevel inheritance can be done at any depth.

Image representation:

Python Multilevel Inheritance Example

class Animal: 
    def eat(self):
      print ‘Eating…’
class Dog(Animal):
   def bark(self):
      print ‘Barking…’
class BabyDog(Dog):
    def weep(self):
        print ‘Weeping…’
d=BabyDog()
d.eat()
d.bark()
d.weep()

Output:
Eating… 
Barking… 
Weeping 

Python Multiple Inheritance

Python Multiple Inheritance

Python supports multiple inheritance too. It allows us to inherit multiple parent classes. We can derive a child class from more than one base (parent) classes.

Image Representation

The multiderived class inherits the properties of both classes base1 and base2.

Let’s see the syntax of multiple inheritance in Python.

Python Multiple Inheritance Syntax
class DerivedClassName(Base1, Base2, Base3): 
     
    . 
    . 
    . 
      

Or

class Base1: 
    pass 
 
class Base2: 
    pass 
 
class MultiDerived(Base1, Base2): 
    pass  

Python Multiple Inheritance Example

class First(object):
  def __init__(self):
    super(First, self).__init__()
    print(“first”)

class Second(object):
  def __init__(self):
    super(Second, self).__init__()
    print(“second”)

class Third(Second, First):
  def __init__(self):
    super(Third, self).__init__()
    print(“third”)

Third();

Output:
first 
second 
third 

Why super () keyword

The super() method is most commonly used with __init__ function in base class. This is usually the only place where we need to do some things in a child then complete the initialization in the parent.

See this example:
class Child(Parent): 
    def __init__(self, stuff): 
        self.stuff = stuff 
        super(Child, self).__init__() 
Composition in Python

Composition is used to do the same thing which can be done by inheritance.

Introduction To Python

Introduction To Python

Why Python was created?
In late 1980s, Guido Van Rossum was working on the Amoeba distributed operating system group and the problem with that was less extensibility. So, he wanted to create a new language that was must be syntax friendly which could access the Amoeba system calls. So, he decided to create a language that was extensible and the new developed language was named as python.

Version Release Data

Python 1.0 (first standard release) January 1994
Python 1.6 (Last minor version) September 5, 2000
Python 2.0 (Introduced list comprehensions) October 16, 2000
Python 2.7 (Last minor version) July 3, 2010
Python 3.0 (Emphasis on removing duplicative constructs and module) December 3, 2008
Python 3.5 (Last updated version) September 13, 2015

Why should a user be choosing Python over other languages:

1.) Easy Elegant Syntax
Programming in Python is fun.
The syntax feels natural.
Easier to understand and write Python code.
Illustration of an code:
     
x = 10
y = 20
sum = x + y
print(sum)
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

2.) Not overly strict :

You dont need to define the type of a variable in Python. Also, it’s not necessary to add semicolon at the end of the statement.
Python enforces you to follow good practices (like proper indentation).
3.) Expressiveness of the language

Python allows you to write programs having greater functionality with fewer lines of code. Here’s a link to the source code of Tic-tac-toe game with a graphical interface and a smart

Story behind the name Python

Guido van Rossum, the creator of the Python language, named the language after the BBC show “Monty Python’s Flying Circus”. He doesn’t particularly like snakes that kill animals for food by winding their long bodies around them and crushing them.

Next

Features of Python

Features of Python

1) Easy to Learn
As you will see, Python is extremely easy to get started with. Python has an extraordinarily simple syntax, as already mentioned.

2) Free and Open Source
Python is an example of a FLOSS (Free/Libré and Open Source Software). In simple terms, you can freely distribute copies of this software, read its source code, make changes to it, and use pieces of it in new free programs. FLOSS is based on the concept of a community which shares knowledge. This is one of the reasons why Python is so good – it has been created and is constantly improved by a community who just want to see a better Python.

3) High-level Language
When you write programs in Python, you never need to bother about the low-level details such as managing the memory used by your program, etc.

4) Portable
Due to its open-source nature, Python has been ported to (i.e. changed to make it work on) many platforms. All your Python programs can work on any of these platforms without requiring any changes at all if you are careful enough to avoid any system-dependent features.

5) Object Oriented
Python supports procedure-oriented programming as well as object-oriented programming. In procedure-oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object-oriented languages, the program is built around objects which combine data and functionality. Python has a very powerful but simplistic way of doing OOP, especially when compared to big languages like C++ or Java.

5) Extensive Libraries
The Python Standard Library is huge indeed. It can help you do various things involving regular expressions,documentation generation, unit testing, threading, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces), and other system-dependent stuff. Remember, all this is always available wherever Python is installed. This is called the Batteries Included philosophy of Python.

PreviousNext

Hello, World

Hello, World

Python is an interpreted programming language, this means that as a developer you write Python files in a text editor and save the file with .py and then put that file into the python interpreter to be executed.

Printing
Programming tutorials since the beginning of time have started with a little program called “Hello, World!

Let’s write our first Python file, called helloworld.py, in any text editor.
     
print(“Hello world!”)
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Code Indentation

This is the most important rule of python programming. In programming language like Java, C or C++, generally curly brackets { } are used to define a code block, but python doesn’t use brackets, then how does python knows where a particular code block ends.

Well python used indentation for this. It is recommended to use tab for indentation, although you can use four spaces for indentation as well.

For example:
if True:
    # this is inside if block
    print(“I Love Python..”)
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

PreviousNext

Python Variables

Python Variables

In most of the programming languages a variable is a named location used to store data in the memory. Each variable must have a unique name called identifier. It is helpful to think of variables as container that hold data which can be changed later throughout programming.

Note: In Python we don’t assign values to the variables, whereas Python gives the reference of the object (value) to the variable.

Variable Declaration
In Python, variables do not need declaration to reserve memory space. The variable declaration or variable initialization happens automatically when we assign a value to a variable.

Assigning value to a Variable
You can use the assignment operator = to assign the value to a variable.

For example:
var = “Python is Awesome”
print(var)
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Note : Python is a type inferred language, it can automatically infer a String and declare another String.

For example:
var = “Python is Awesome”
# assigning a new value to var
var = “I Love Python…”
print(var)
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

Valid Variable Names
The naming of variables follows the more general concept of an identifier. A Python identifier is a name used to identify a variable, function, class, module or other object.
A variable name and an identifier can consist of the uppercase letters “A” through “Z”, the lowercase letters “a” through “z” , the underscore _ and, except for the first character, the digits 0 through 9. Python 3.x is based on Unicode. This means that variable names and identifier names can additionally contain Unicode characters as well. But in Python 2, identifiers can only be ASCII letters, numbers and underscores.
Identifiers are unlimited in length. Case is significant. The fact that identifier names are case-sensitive can cause problems to some Windows users, where file names are case-insensitive for example.

PreviousNext

Python Data Types

Python Data Types

Python has five standard Data Types :

Numbers
String
List
Tuple
Dictionary

Tip :Python sets the variable type based on the value that is assigned to it :
var = “Python is Awesome”
print(var)
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

1) Numbers : Python supports four types of numbers – int,long,float and complex

Type Format Description
int X=200 Signed Integer
long X=1370L (L) Long integers,they can also be represented in octal and
float X=69.740 (.) Floating point real values
complex X=4+21j Complex Number

A complex number consists of an ordered pair of real floating-point numbers denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.

To define an integer, use the following syntax:

myInt = 6
print myInt
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

To define a floating point number, you may use one of the following notations:
myFloat = 6.0
myFloat = float(6)
print myFloat
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

2) String :
String variables are enclosed with quotes.
Python uses single quotes ” double quotes “” and triple quotes “””

Program illustration on String :
firstName = ‘Asish’
lastName = “Samantaray”
app = “””Python Tutorial”””
print firstName
print lastName
print app
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

3) Lists :
Lists are the most versatile of Python’s compound data types. A list contains items separated by commas and enclosed within square brackets []. To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type.

Program illustraion on lists in Python:

list = [ ‘python’, 619 , 3.141, True ]
tinylist = [143, ‘Asish’]

print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd till 3rd
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

4) Tuple :
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

The main differences between lists and tuples are: Lists are enclosed in brackets [] and their elements and size can be changed, while tuples are enclosed in parentheses () and cannot be updated. Tuples can be thought of as read-only  lists.Program illustraion on Tuple in Python:

tuple = ( ‘python’, 619 , 3.141, True )

print tuple          # Prints complete tuple
print tuple[0]       # Prints first element of the tuple
print tuple[1:3]     # Prints elements starting from 2nd till 3rd
print tuple[2:]      # Prints elements starting from 3rd element
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

4) Dictionary :
This is a very powerful datatype to hold a lot of related information, Dictionaries in Python are lists of “Key”:”Value” pairs.values can be extracted by the key name.

Dictionaries are created by using braces {} with pairs separated by a comma ,.

Program illustraion Dictionary :
thisdict = {
  “brand”: “Lamborghini”,
  “model”: “Huracan”,
  “year”: 1963
}
print(thisdict)
Copy
Note: Copy and Paste Code into Compiler
Open Compiler 

PreviousNext