Sunday, November 29, 2015

Python - Calling functions without instantiating instances of objects

An quick explanation on how to call a function from python files without instantiating and instance of an object.  The example python file list below contains a main.py and a mylist.py files.  The mylist.py file does not contain any class object heading information. It is just a simple python file that can be imported and used without instantiating an instance to create an object.  In the main.py file is an import mylist that imports the functions previously defined.  Very similar to 'using' statement at the top of C# files when referencing capabilities from other libraries.

main.py:
import sys
import mylist

__author__ = 'linos'


def main():
    a = mylist.printList()
    print(__author__)
    #a.printList()

if __name__ == '__main__':
    main()





mylist.py:
__author__ = 'linos'

#This is not a class, but rather just another python file.#As you can see here, there are no imports or indentation on the def listed below.#The file behaves as an extention from the Main.py file when calling the functions.
def printList():
    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