Creating your own Python Package
Object-oriented programming is a type of programming in which programmers define the data type of a data structure and also the type of operations that can be applied to the data structure.
Let’s first look at the basics of object-oriented programming. Class is a blueprint for the object. Object is simply a collection of attributes(variables) and methods (functions). Attributes are the characteristics of an object. Methods are the tasks performed on the object.
Let’s understand this with an example. ‘Shirts’ can be considered as a Class. ‘Shirt1’ and ‘Shirt2’ are different objects of the Class ‘Shirts’. ‘Color’, ‘Size’, and ‘Price’ are the attributes of each object of the Class ‘Shirt’. ‘Doubling the price’, and ‘Changing color’ are the methods performed on each object of the Class ‘Shirt’. The syntax is as given below.
The output of the above snippet of code is as given below :-
Python is an object-oriented programming language. The various in-built packages in Python are all built on the concept of object-oriented programming. Now we’ll create our own python package that calculates the mean, standard deviation and plots the histogram of any user input data. The snippet of code is as given below.
We create an object of class ‘guassian’ by specifying the mean and standard deviation.
We can also create an object of class ‘guassian’ by reading the data from a text file. In text file, each line is a number.
The histogram is as plotted below.
Let’s look at ‘Magic Methods’. Magic methods are special methods that you can define in your classes. The rules of operation are as specified by user. We look at 2 magic methods below.
__add__ method returns the addition of 2 objects of a class.
__repr__ method returns the object representation.
__add__ method adds the 2 objects ‘guassian_one’ and ‘guassian_two’. The means are added as sum of means and the standard deviations are added as square root of sum of squares of standard deviations.
__repr__ method returns the ‘guassian_three’ representation in the following format :- mean 7, standard deviation 10.63
We have created our own python package that can read user input data, calculate mean and standard deviation, plot the histogram and can add 2 sets of data.