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:

0 comments:

Post a Comment