Monday, November 30, 2015

Python - Create Instance, Initialize Constructors, and verify objects

The example listed below demonstrates how to create an instance of an object and run a method. Note, when initializing myCompEmp1 and myCompEmp2, the variables passed in match the parameters the __init__ takes.  This is how the constructor initializes the variables for future use.  The method displayEmployee will print out the variables previously passed in to the constructor.  The displayCount method will display the total number of instances created.  Note, this was accomplished by initializing empCount variable in companyA to zero.  Everytime a new instance is created, the constructor will add one.




main.py
import sys
import mylist
import anotherList
import companyA

__author__ = 'linos'

def main():

    myCompEmp1 = companyA.Employee("Zara",4000)
    myCompEmp1.displayEmployee()
    myCompEmp1.displayCount()

    myCompEmp2 = companyA.Employee("Bill",1000)
    myCompEmp2.displayEmployee()
    myCompEmp2.displayCount()


if __name__ == '__main__':
    main()

companyA.py
__author__ = 'linos'


class Employee:
    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)

No comments:

Post a Comment