Python - How to Define CLASS in Script

Here's an example of the Python define class in Script. Here you can create CLASS in Script and run and test it.

You are aware that Python supports Classes as part of Object-Oriented Programming Capabilities. You can create an Object from the Class. Also, you can use the methods of that.

Here is a logic you can create a script with Class and Objects


Python class within the script


  • Sample code
  • Actual code in Script
  • Run Script

Python class within the script


Sample Code - Below is the code that gives indentation errors. However, I have corrected the actual script.


class Employee:
"""Base class"""
empCount = 0


def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1


# can also be written as Employee.empCount = Employee.empCount + 1
def displayEmployee(self): # function is defined here
print "Name : ", self.name, ", Salary: ", self.salary


# "emp1 is the first object of Employee class"
emp1 = Employee("Akhil", 2000)


# "emp2 is the second object of Employee class"
emp2 = Employee("Suresh", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)

Actual Code in the Script



Python Script poly.py. Below is the command you need to create a script in Ubuntu (This example tested in Ubuntu). You can do any Linux operating system for practice.


$ vim poly.py


Python Class and Object in a Script


Logic:
 

In python,' init' is a mandatory method with 'self' you need to give. The arguments 'name' and 'salary' are optional to you. Here I used two objects of Employee - emp1 and emp2. The Employee is the base class.


These objects used the "displayEmployee" method. According to the print definition, you got the below output details.


The last print has two characters. One is %d and %. The %d, pads a blank. If you want more, you can write %2d, %3d, and so on.

Run the Script


From Python Console, get the .py module using the "import" command. It runs as and when the import completes.

  • The command to import is - >>> import poly.py
  • When I imported, it displayed the messages as expected.

Comments

Popular posts from this blog

How to Fix Python Syntax Errors Quickly

Hyperledger Fabric: 20 Real Interview Questions

7 AWS Interview Questions asked in Infosys, TCS