Start Python Scripting in linux
#!/bin/bash/python
Print the out put in python
>>> print "Hello, Python"
Hello, Python
Exit form python
>>> exit()
Install Python in Linux
Using YUM
#yum install python
#python --verson
Using ZIP File
Here are the simple steps to install Python on Unix/Linux machine.
- Open a Web browser and go to https://www.python.org/downloads/.
- Follow the link to download zipped source code available for Unix/Linux.
- Download and extract files.
- Editing the Modules/Setup file if you want to customize some options.
- run ./configure script
- make
- make install
Python file Extension
Every Python program file ends with the .py format
example.py
Execute the Python script in Linux
$chmod -x example.py
$./example.py
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.3. This number can vary slightly in course of time.
All the keywords except
True
, False
and None
are in lowercase and they must be written as it is. The list of all the keywords are given below.False | class | finally | is | return |
None | continue | for | lambda | try |
True | def | from | nonlocal | while |
and | del | global | not | with |
as | elif | if | or | yield |
assert | else | import | pass | |
break | except | in | raise |
Python Identifiers :-
A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.
Here are naming conventions for Python identifiers −
- Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
- Starting an identifier with a single leading underscore indicates that the identifier is private.
- Starting an identifier with two leading underscores indicates a strongly private identifier.
- If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
Python Classes Tutorial
Welcome to lesson six, Classes tutorial, which is a part of the Python Course offered by Simplilearn. This lesson will provide detailed information on classes.
Objectives
After completing this lesson, you'll be able to:
- Define a class and its advantages
- Describe the method to create a class
- Describe the method to add functions to a class
- Describe the built-in class attributes
Python Classes
Python is an OOPS language so you can create classes and objects. Before creating classes and objects, you need to know the need of creating them in the first place.
Many built-in types of Python are being used every day. What if someone wants his own data types whose behavior and properties should be defined too.
For this, there should be a complete control over the defined behavior of this data type. You can do this by creating classes. Classes are nothing but user-defined data types. A class is just a blueprint defining the type of data that a user-defined data type can store and the kinds of operations that are supported by it.
The previous lessons elaborated on creating various variables of data types like variables of integer, string, float, and so on.
Here, we talk about creating variables of your own defined data types. These variables are called objects. Classes represent a simple way of depicting real-world things in the form of data types in programming.
Suppose you want to represent a car and store its properties and show what kind of things a car can perform. In such cases, you can create a car class which contains variables and functions.
Variables
For defining the properties of a car, you can create different variables inside the car class to store various properties like model number, build year, brand name, and so on.
Functions
The functions inside a class represent the kind of operations the real world things can do. So in the given example, a car can have functions like start, stop, apply brake, and so on.
Objects
As explained earlier, objects are the variables of a class data type. As you can create multiple variables of a data type (where each variable is capable of handling a different value), you can also create multiple objects of a class. Each object can store different values too.
In the given example, let's say you want to create an object car1 of type Car, then you can just write the given statement.
car1 = Car( )
You can also pass initial values to depict the properties of the car variable, as shown in the example.
car2 = Car(“Test model” , “Test Brand” )
Creating a Basic Class
To understand how a class can be created, let's see the example shown below.
Here you want to create a class named Vehicle. This class should be able to store the model name and the brand name for the class Vehicle.
You can create this class by using the keyword ‘class’, followed by the class name. After this, you can add various property names that you would want to include in this class.
class Vehicle:model_name = “model x”brand_name = “Brand y”
To create an object for this class, you can just write the given statement.
>>>car1 = Vehicle()
This will create an object named ‘car1’ of type vehicle.
Accessing Variables of a Class
After creating an object, you may need to access the value stored in different variables of that object. You can do this by using a dot operator. Append a dot after the name of an object for which you want to access a specific variable, and then give the name of that variable. You will get the access to the desired value.
In the given example, If you want to access the model name of the variable car1, you can write the given print command. They will then print the model name for that particular object.
>>> print car1.model_name
output : model x
Similarly, you can print other variables of the same object as shown for printing a brand name in the given example.
>>> print car1.brand_name
output : brand y
Adding Functions to a Class
Till now, you have seen how variables are added to classes. To understand how to add functions to classes, you just need to define the function in the same way you had defined earlier.
But this time, it's definition should be written inside the class body. See the example below.
class Vehicle:model_name = “model x”brand_name = “Brand y”def start(self):print “Starting Vehicle...”defstop(self):print “Stop Vehicle...”
A start and a stop function have been created. If the start function is called, it should print “starting vehicle”. And if the stop function is called, it should print “stop vehicle”.
Note that the first argument to each method is self. Python adds the self-argument to the list. You do not need to include it when you call the methods.
Built-in Class Attributes
Built-in attributes can be accessed by using a dot operator like any other attribute. There are five types of built-in class attributes:
- _dict_ attribute gives a dictionary containing the class’s namespace.
- _doc_ attribute gives a class documentation string. It will return nothing if the documentation is not defined.
- _name_ attribute gives a class name.
- _module_ attribute gives the name of a module in which the class is defined. It's called _main_ in the interactive mode.
- _bases_ attribute returns an empty tuple containing the base classes.
_Init_Function
Python classes have a special function called Init. It's called the class constructor, or initialization method that python calls when you create a new instance of such a class. It is called in a code when you create an object.
It allocates spaces for various objects. This function takes care of initializing objects. This means that it takes care of assigning values to variables of objects passed by the user.
As with other functions in a python class, the first argument to each method is self. Python then adds the self-argument to the list. You do not need to include it when you call the methods.
Example of Defining and Using a Class
To understand how to create a class in python, see the example given below:
class Student(object) :name = “”pass = Truedef __int__(self, name):self.name=namedef is_pass(self):return self.pass
To create a student class, there are two variables in this class. The first variable is ‘name’, which is used to store the name of a student. The second variable is the ‘pass’ variable that contains the value True.
Seeing further, the constructor has also been defined. The first argument of the constructor is self, as explained in the previous sections.
The second argument is ‘name’. A name passed by the user has been assigned to the variable of this object. Similarly, one more function pass has been created above, which returns the value of the variable pass.
To explain the same example in more detail, it's important to know how to use a class.
Consider the example shown below.
## Defining objectstudent1 = Student(“David”)##Using the objectprint student1.is_pass()Output : True
Create the object of the class student and assign the name ‘David’ to the name variable. On calling the init method and passing David to it, you can access the name variable of this object, or call it. This is called with the pass function using a dot operator. It will return a relevant value.
Summary
Let's summarize the topics covered in this lesson.
- A class is a user-defined data type that’s used as a blueprint to create multiple objects. It is made of variables and functions.
- Objects are variables of classes. You can create multiple objects of a class and each object can have different values for its variables.
- The dot operator is used to access the values stored in different variables of that object.
- Every Python class follows built-in attributes and they can be accessed using the dot operator like any other attribute.
- Python classes have a special function called __init__, which is a class constructor.
Conclusion
With this, we have come to an end of this lesson on Python Classes.
UNDERSTANDING SELF AND __INIT__ METHOD IN PYTHON CLASS.
Before understanding the "self" and "__init__" methods in python class, it's very helpful if we have the idea of what is a class and object.
Class :
Class is a set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality.
In technical terms we can say that class is a blue print for individual objects with exact behaviour.
Object :
object is one of instances of the class. which can perform the functionalities which are defined in the class.
self :
self represents the instance of the class. By using the "self" keyword we can access the attributes and methods of the class in python.
__init__ :
"__init__" is a reseved method in python classes. It is known as a constructor in object oriented concepts. This method called when an object is created from the class and it allow the class to initialize the attributes of a class.
How can we use "__init__ " ?
Let's consider that you are creating a NFS game. for that we should have a car. Car can have attributes like "color", "company", "speed_limit" etc. and methods like "change_gear", "start", "accelarate", "move" etc.
class Car(object): """ blueprint for car """ def __init__(self, model, color, company, speed_limit): self.color = color self.company = company self.speed_limit = speed_limit self.model = model def start(self): print("started") def stop(self): print("stopped") def accelarate(self): print("accelarating...") "accelarator functionality here" def change_gear(self, gear_type): print("gear changed") " gear related functionality here"
Lets try to create different types of cars
maruthi_suzuki = Car("ertiga", "black", "suzuki", 60) audi = Car("A6", "red", "audi", 80)
We have created two different types of car objects with the same class. while creating the car object we passed arguments "ertiga", "black", "suzuki", 60 these arguments will pass to "__init__" method to initialize the object.
Here, the magic keyword "self" represents the instance of the class. It binds the attributes with the given arguments.
Usage of "self" in class to access the methods and attributes
Case: Find out the cost of a rectangular field with breadth(b=120), length(l=160). It costs x (2000) rupees per 1 square unit
class Rectangle: def __init__(self, length, breadth, unit_cost=0): self.length = length self.breadth = breadth self.unit_cost = unit_cost def get_perimeter(self): return 2 * (self.length + self.breadth) def get_area(self): return self.length * self.breadth def calculate_cost(self): area = self.get_area() return area * self.unit_cost # breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000 r = Rectangle(160, 120, 2000) print("Area of Rectangle: %s cm^2" % (r.get_area())) print("Cost of rectangular field: Rs. %s " %(r.calculate_cost()))
As we already discussed "self" represents the same object or instance of the class. If you see, inside the method "get_area" we have used "self.length" to get the value of the attribute "length". attribute "length" is bind to the object(instance of the class) at the time of object creation. "self" represents the object inside the class. "self" works just like "r" in the statement "r = Rectangle(160, 120, 2000)". If you see the method structure "def get_area(self): " we have used "self" as a parameter in the method because whenever we call the method the object (instance of class) automatically passes as a first argument along with other argumets of the method.If no other arguments are provided only "self" is passed to the method. That's the reason we use "self" to call the method inside the class("self.get_area()"). we use object( instance of class) to call the method outside of the class definition("r.get_area()"). "r" is the instance of the class, when we call method "r.get_area()" the instance "r" is passed as as first argument in the place of self.
Self :
>>> class className:
... def createName(self,name):
... self.name=name
... def displayName(self):
... return self.name
... def saying(self):
... print "hello %s" % self.name
...
...
check class name created or not
>>> className
<class __main__.className at 0x7f89f3b14530>
Create objects with methods
>>> first=className()
>>> second=className()
>>> first.createName('Sandya')
>>> second.createName('Govardhan')
>>> first.displayName()
'Sandya'
>>> second.displayName()
'Govardhan'
>>> first.saying()
hello Sandya