Wednesday, October 31, 2018

Class data type in Python

In object-oriented programming we write classes that represent real-world things and situations, and then create objects based on these classes. Writing a class is nothing but defining the general behavior that a whole category of objects can have.

When objects are created  from the class, each object is automatically equipped with the general behavior; later we can give each object whatever unique traits we desire.

Creating a class

Creating a class in Python is quite easy. Refer to the following syntax:

         class <class name >(<parent class name>):
                  <method definition-1>
                  <method definition-n>

Let us create our first class, a very simple example of a class which will set position of employee and then print the position.

class Employee():
  
    def setPosition(self, position):
        self.position= position.title()


    def getPosition(self):
        return self.position
  
emp1 = Employee()

emp2 = Employee()

emp1.setPosition('tester')

emp2.setPosition('developer')
 
print(emp1.getPosition())


print(emp2.getPosition())

We started with the class definition, the keyword class defines a class Employee. Every employee has a position so this information goes in our class. The Employee class has two other methods defined: setPosition() and getPosition(). The setPosition() method allow us to associate our employee with his position and getPosition() method merely prints the position of employee.

First, emp1 is created as an instance of Employee. Notice the empty parentheses following the word
Employee. This causes the class definition to produce an object that you can use. I have given emp1 a position using the setPosition() method I defined earlier. The values can be retrieved using the accessor methods getPosition().

Let's run this program and see the output which should print the position of the employee. As seen in the output below, Tester is the position of this employee.



The parameter self

The main difference between methods and functions is this additional parameter called self; self refers back to the object upon which the operation is taking place, so in this instance self refers to emp1.

The name of the object is passed to any methods called on it, along with any additional arguments. It is also used in the class definition where values are assigned to attributes. Attributes are like variables
contained within the object, such as self.position. These attributes can be accessed from outside the object as (in this instance) emp1.position. In most cases, however, we don't want to access them like this because we will usually want to process or format the data using a class method like setPosition()

The __init__() Method

If we create an instance variable, as shown in the first example, then we would not get benefit of making a class. You can see repeatable code for both the instances. So we would not have to set the variable 'position' all the time. In order to make it automatically, we will use the special method __init__() function.

The __init__() Method is a special method Python runs automatically whenever we create a new instance of a class. This method has two leading underscores and two trailing underscores, a convention that helps prevent Python’s default method names from conflicting with your method names. The __init__() Method works as the class's constructor. When a user instantiates the class, it runs automatically. If we don't define the  __init__() Method , our default base class object provides it. Thus, our first program can be written as shown below using the __init__() method


class Employee():
   
    def __init__(self,position):
       
        self.position = position
   
    def setPosition(self):
        self.position= position


    def getPosition(self):
        return self.position.title()
   
emp1 = Employee('tester')
emp2 = Employee('developer')


print(emp1.getPosition())
print(emp2.getPosition())


We define the __init__() method to have two parameters: self, position. The self parameter is required in the method definition, and it must come first before the other parameters. It must be included in the definition because when Python calls this __init__() method later (to create an instance of Employee), the method call will automatically pass the self argument.

Every method call associated with a class automatically passes self, which is a reference to the instance itself; it gives the individual instance access to the attributes and methods in the class. When we make an instance of Employee, Python will call the __init__() method from the Employee class. We’ll pass Employee() a position as an argument; self is passed automatically, so we don’t need to pass it. Whenever we want to make an instance from the Employee class, we’ll provide value for only the position parameter.

Any variable prefixed with self is available to every method in the class, and we’ll also be able to access these variables through any instance created from the class. self.position = position takes the value stored in the parameter position and stores it in the variable position , which is then attached to the instance being created. Variables that are accessible through instances like this are called attributes.

The Employee class has two other methods defined: setPosition() and getPosition(). Because these methods don’t need additional information like position, we just define them to have one parameter, self. The instances we create later will have access to these methods.

We created two instances of the Employee class,

emp1 = Employee('tester')
emp2 = Employee('developer')


By this we we tell Python to create two employees whose designations are tester and developer. When Python reads these lines, it calls the __init__() method in Employee with the arguments 'tester' and 'developer'. The __init__() method creates the instances representing these particular employees and sets their position attributes using the values we provided. The __init__() method has no explicit return statement, but Python automatically returns an instance representing these employees. We store those instances in the variables emp1 and emp2.

After we create an instance from the class Employee, we can use dot notation to call any method defined in Employee. In the code emp1.getPosition() and emp2.getPosition() we used the instances we created to call the getPosition() method defined in the Employee class.

When Python reads emp1.getPosition() and emp2.getPosition(), it looks for the method getPosition() in the class Employee and runs that code given the output shown below.





Here our introduction to Python Class comes to an end. Next we'll start working with Classes and Instances thereby exploring the real potential of classes.
 
So keep learning Python as Python is easy to learn!
Share:

Tuesday, October 30, 2018

Python is an Object oriented language

Like other programming languages, Python language also supports object oriented programming. Object orientation can help to reduce complexity, particularly in long programs. It also encourages
programmers to re-use existing, tested code because it is possible to create objects that inherit the
majority of their attributes and methods from an existing class, leaving the programmer to add or
override the pieces that specifically need to be different. Using the principle known as inheritance,
specific objects can be created out of general ones, producing a family tree of objects similar to the
classification of natural species.

Let's first understand what object-oriented programming is. Before this concept was introduced, we were coding in procedural programming, that is, going line by line. At this level, you need not understand what is procedural programming but certainly there is one example to illustrate it, that is, C language. In procedural programming, there were a lot of complexities and above all procedural programming had negligible code reuse concept.

The concept of object-oriented programming was seen to solve many problems, which procedural programming did not solve. In object-oriented programming, everything mimics just like a real-world object. In the real world, everything is an object. An object can have state and behavior. An object in the real world can communicate with another object. For example, a shape object in the real world has state and behavior. OOPs is based on four pillars. They are:
  1. Polymorphism
  2. Inheritance
  3. Abstraction
  4. Encapsulation
We have already seen what can be achieved using the methods provided by the basic data types. Now we shall first go through some basic concepts of OOP.

Key concepts

Actually OOPs is a vast topic that needs to be covered at the intermediate level. In case of Python
programming, however, we will cover some key concepts which will make programming using OO approach easier.

1. Class: Class is considered as a blueprint for object creation. It can be understood as a factory to produce objects. It provides a template for creating an object and specifying its behavior through means of methods and state through means of variable instance name.

2. Objects: An object is an instance of a class. An object can have state and behavior or attributes. The objects basically bundles a set of related states and behaviors, for example, a shape has state (name) and behavior (round, square).

3. Inheritance: In object-oriented programming, the child class can inherit many properties from the parent class. Here, we mean that the child class can use an existing method or behavior, which the parent class has defined and use them accordingly in their class. Inheritance can be a single inheritance or multiple inheritance. Single inheritance, as the name suggests, refers to only one parent, while multiple inheritance refers to inheriting the property from multiple parents.

4. Polymorphism: In OOPs, an object can have many forms through means of different attributes. To
simplify, in our case, we can understand it by methods with the same name but having different outputs.

5. Abstraction: Here, we hide the necessary details and are only interested in showing the relevant details to the other intended user. Here, by other intended user we mean another software application, or another class, or other client who will be the end users of the program.

6. Encapsulation: This refers to hiding the necessary methods and their relevant details from the outside world. A class can be treated as a best example, which provides encapsulation to the methods and relevant instances.

Object orientation can help to reduce complexity, particularly in long programs. It also encourages
programmers to re-use existing, tested code because it is possible to create objects that inherit the
majority of their attributes and methods from an existing class, leaving the programmer to add or
override the pieces that specifically need to be different. Using the principle of inheritance, specific objects can be created out of general ones, producing a family tree of objects similar to the classification of natural species.

Central to the concept of object orientation is the class—a template for creating your own data types. A data type may be a person, for example, each of whom has unique aspects that might be specified by data such as first_name, last_name, Age, Sex, and Location.

Think of a class as a noun, representing objects that are described by unique aspects. These aspects are technically referred to in OOP as attributes. Class definitions are sometimes referred to as templates, as their entire purpose is to serve as a blueprint or model of class objects for you to use in your programs. Classes form the basis of a whole new style of programming. You have already moved the focus of your programs from simple top -down scripts to function-driven applications. Classes enable you to move the action into custom-built objects, which can contain both data (attributes) and commands (methods). Creating objects involves a further stage of abstraction from function-driven programming and provides a means of modeling real-world constructs as single entities in your code.

Objects are the primary means of representing data in Python. All data in a Python program is represented by some type of object or by the relationship between objects. A class is a template for an object that bundles up several related pieces of data and defines a bunch of functions for accessing and manipulating that data. A class definition is similar to a function definition in that nothing happens until you tell Python to make an object based on the class template; this is called creating an instance of that class. Even then, any methods that are part of the class won't do anything until they are specifically called, just like functions.

Organizing your data into self contained units makes it easier to figure out problems using the same sort of logic that you are used to using in real-world situations. Many programmers find that object orientation allows their code to grow in a more natural way than constantly having to create new functions from scratch.

Lets say we have a class Pizza. This would contain general attributes that could be applied to any object of the same class. You could then derive further subclasses from these base class, so Pizza could become the parent to several child classes, such as Veg and Non-veg. Each of these children would contain new attributes specific to their type, but they’d also inherit the general attributes of a  Pizza.

Here our introduction to Python as a OOL comes to an end. Next we'll start using the concepts introduced in this post to make programs. I'd suggest to read in more details about OOP as in real world programs we use OOP.

So keep learning Python as Python is easy to learn!


Share:

Saturday, October 27, 2018

Modules in Python

While programming you might have come across with a situation where there is a function that you want to use in many programs without copying it into each program. For example the greet_emp() we made in previous post. This can be used by various departments who have newly joined employees. Thus such functions should be stored in a in a separate file called a module and then importing that module into your main program.

A module usually contains statements that have some relation with each other, such as a function and its related declarations or unrelated statements, which are written to perform a specific task. Modules can be made to interact with each other to access each other’s attributes.

To be able to use a piece of code stored in a module, a module should be shared. The process of bringing in the attributes, such as variables and functions, of one module into another or at the interpreter itself is called importing. Importing is the basis of a module in Python. It is this feature that allows variables and functions declared in one module to be shared in different modules. An import statement tells Python to make the code in a module available in the currently running program file.

In other words, a module is a Python file containing Python definitions and statements. The filename is the name of the module with the .py extension appended. Here’s an example of a simple module -

def greet_emp(enames):
   
    for name in enames:
       
        greeting = "Welcome aboard " + name + "!"
        print(greeting)


Use any text editor to write the preceding code and save it as greet_emp.py. Storing your functions in a separate file allows you to hide the details of your program’s code and focus on its higher-level logic. It also allows you to reuse functions in many different programs. When you store your functions in separate files, you can share those files with other programmers without having to share your entire program. Knowing how to import functions also allows you to use libraries of functions that other programmers have written.

There are several ways to import a module, let's see each of these briefly.

1. Importing an entire module

Let us use the module greet_emp.py which we have created recently. We'll use this module in a program welcome_emp.py, which will welcome new employees in a department. Here is the code snippet -

import greet_emp
   
users = ["Bob","Ted", "Joey","Chris","Mac"]
greet_emp.greet_emp(users)


When Python reads this file, the line import greet_emp tells Python to open the file greet_emp.py and copy all the functions from it into this program. You don’t actually see code being copied between files because Python copies the code behind the scenes as the program runs. All you need to know is that any function defined in greet_emp.py will now be available in welcome_emp.py.

To call a function from an imported module, enter the name of the module you imported, greet_emp, followed by the name of the function, greet_emp(), separated by a dot, i.e greet_emp.greet_emp().When we run this program we'll get the following output -





This first approach to importing, in which you simply write import followed by the name of the module, makes every function from the module available in your program. If you use this kind of import statement to import an entire module named mod_name.py, each function in the module is
available through the following syntax - mod_name.func_name()


2. Importing a specific module

It is also possible to import a specific function from a module. Here’s the general syntax for this approach

from mod_name import func_name

Let us add one more function goodbye_emp() in our module greet_emp.py. The code is shown below-

def goodbye_emp(ename):
   
    farewel = "\nGood luck for your future endeavors " + ename + " we will miss you"
    print(farewel)


In order to use this function in our program farewel.py we'll import goodbye_emp() as follows -

from greet_emp import goodbye_emp

goodbye_emp('Veevaeck')


The output of the program is shown below-



It's possible to import as many functions as we require from a module by separating each function’s name with a comma -

from mod_name import func_name1, func_name2, func_name3

Thus to use both greet_emp() and goodbye_emp() in a new program hrgreetings.py we will use the following statement -

from greet_emp import greet_emp,goodbye_emp

The program is shown below -

from greet_emp import greet_emp,goodbye_emp

users = ["Bob","Ted", "Joey","Chris","Mac"]
greet_emp(users)
goodbye_emp('Veevaeck') 


When we run this program we'll get the following output -



In case you haven't notice, with this syntax, you don’t need to use the dot notation when you call a
function. Because we’ve explicitly imported the functions greet_emp and goodbye_emp in the
import statement, we can call it by name when we use the function.


3. Importing a function using alias

We have used a common name greet_emp for our module as well as function which sometimes be confusing or conflict with an existing name in our program. Also  if the function name is long, you can use a short, unique alias—an alternate name similar to a nickname for the function.

We’ll give the function this special nickname when we import the function. So in our program farewel.py we'll import goodbye_emp() as follows -

from greet_emp import goodbye_emp as ge

ge('Veevaeck')

Here we have given the function goodbye_emp() an alias, ge(), by importing goodbye_emp as ge. The as keyword renames a function using the alias you provide.

Any time we want to call goodbye_emp() we can simply write ge() instead, and Python will run the code in goodbye_emp() while avoiding any confusion with another goodbye_emp() function you might have written in this program file.

The general syntax for providing an alias is: from module_name import function_name as fn

4. Importing a module using alias

We can also provide an alias for a module name. Giving a module a short alias, like g for goodbye_emp , allows you to call the module’s functions more quickly.

Calling g.goodbye_emp() is more concise than calling goodbye_emp.goodbye_emp(). Thus our program welcome_emp.py, can be re-written as follows -

import greet_emp as g
   
users = ["Bob","Ted", "Joey","Chris","Mac"]
g.greet_emp(users)


The module greet_emp is given the alias g in the import statement, but all of the module’s functions retain their original names. Calling the functions by writing g.greet_emp() is not only more concise than writing goodbye_emp.goodbye_emp(), but also redirects your attention from the module name and allows you to focus on the descriptive names of its functions. These function names, which clearly tell you what each function does, are more important to the readability of your code than using the full module name.

The general syntax for this approach is: import mod_name as mn

5. Importing all functions in a module

We can tell Python to import every function in a module by using the asterisk (*) operator .The re-written program hrgreetings.py is shown below -

from greet_emp import *

users = ["Bob","Ted", "Joey","Chris","Mac"]
greet_emp(users)
goodbye_emp('Veevaeck')


The asterisk in the import statement tells Python to copy every function from the module greet_emp into this program file. Because every function is imported, you can call each function by name without using the dot notation. However, it’s best not to use this approach when you’re working with larger modules that you didn’t write: if the module has a function name that matches an existing name in your project, you can get some unexpected results. Python may see several functions or variables with the same name, and instead of importing all the functions separately, it will overwrite the functions.

The best approach is to import the function or functions you want, or import the entire module and use the dot notation. This leads to clear code that’s easy to read and understand. I include this section so you’ll recognize import statements like the following when you see them in other people’s code:

from mod_name import *

With this our discussion over functions in Python is completed. Make some more programs and use the concepts learned so far. A thorough understanding of modules is a must for Python Programming due to their utility in real world projects.

So keep practicing and learning Python as Python is easy to learn!
Share: