Auto AdSense

Saturday, 24 January 2015

Python Object Oriented - Classes






  • Creating Classes:
    The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows:
    class ClassName:
    'Optional class documentation string'
    class_suite

    The class has a documentation string which can be access via ClassName.__doc__.

    The class_suite consists of all the component statements, defining class members, data attributes, and functions.
    Example:
    class Employee:
    'Common base class for all employees'
    empCount = 0

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

    def displayCount(self):
       print "Total Employee %d" % Employee.empCount

    def displayEmployee(self):
       print "Name : ", self.name, ", Salary: ", self.salary
  • Creating instance objects:
    "This would create first object of Employee class"
    emp1 = Employee("Zara", 2000)
    "This would create second object of Employee class"
    emp2 = Employee("Manni", 5000)
  • Accessing attributes:
    You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows:

    emp1.displayEmployee()
    emp2.displayEmployee()
    print "Total Employee %d" % Employee.empCount

No comments:

Post a Comment