Sunday, November 29, 2015

Python - Calling functions after instantiating instance of an object

An quick explanation on how to call a function after importing the python file (as reference), then creating an instance of an object and calling a function to run.  The following example is very simple since it does not care about input parameters to the printList() function.

main.py:

import sys
import anotherList

__author__ = 'linos'


def main():

    
    print(__author__)

    #Create an instance of mylistObject and assign it to the variable mylistObj
    mylstObj = anotherList.mylistObject()
    #Call the printList function that takes not arguments. 
    mylstObj.printList()

    print(sys.version)


if __name__ == '__main__':
    main()



anotherList.py:
__author__ = 'linos'
class mylistObject:

    #Allows you to control how objects are initialized.  The __init__ is a special method within a class called the constructor or initialization method.  The pass in this example is used to quickly setup the __init__ without having it setup or assigning any variables.
    def __init__(self):
        pass
    def printList(self):
        aList = ["list1", "list2", "list3"]
        print(aList)
        print(aList[1])
        print(len(aList))
        aList.append("list4")
        print(len(aList))
        print(aList)
        aList.pop()
        print("Test", aList)
        aList.insert(2, "list0")
        print(aList)


No comments:

Post a Comment