Skip to content

Instantly share code, notes, and snippets.

@evitolins
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evitolins/6bd124b8f7955f21bd28 to your computer and use it in GitHub Desktop.
Save evitolins/6bd124b8f7955f21bd28 to your computer and use it in GitHub Desktop.
Python: Modules, Classes & Objects

Python: Modules, Classes & Objects

So in Python you have 3 major tools for code organization…Modules, Classes, & Objects

Modules:

Python modules are pretty much just a single python file. You can think about it as giving your variables and functions a specific namespace to reference within another python script. For example: The code below imports the contents of "mySampleModule.py" to allow all it's contents to be used in another python script under it's namespace (by default, the filename).

import mySampleModule

To then run a function from this module, you would then write something like this…

mySampleModule.sampleFunction()

or to access a variable within a module…

mySampleModule.sampleVariable

You can also import a module and assign an alias (alternate namespace) like this… allowing code be a bit less bloated. The sample below is the same as the last 3 examples together.

import mySampleModule as msm
msm.sampleFunction()
msm.sampleVariable

Classes & Objects:

A Class is a concept similar to a module, as it can also contain it's own variables and functions. The difference is it allows the user to create multiple instances of “objects”. Conceptually, you can think of this as similar to referencing multiple instances (objects) of a rig (class) within a scene: The rig is referenced from the same file, but you can alter and animate each one differently.

This is a decent reference/tutorial explaining their differences: http://learnpythonthehardway.org/book/ex40.html

class Person():
def __init__(self):
self.firstName = 'unknown'
self.lastName = 'unknown'
def setFirstName(self, name):
self.firstName = name
def setLastName(self, name):
self.lastName = name
def getFullName(self):
return self.firstName + ' ' + self.lastName
fred = Person() #__init__ is run immediately
bob = Person() #__init__ is run immediately
bob.firstName # currently equals 'unknown'
bob.setFirstName('Fred')
bob.setLastName('Johnson')
bob.firstName # currently equals 'Fred'
print(bob.getFullName()) # 'Fred Johnson'
fred.firstName # currently equals 'unknown'
fred.setFirstName('Bob')
fred.setLastName('Malooga')
fred.lastName # currently equals 'Malooga'
print(fred.getFullName()) # 'Bob Malooga'
fred.setLastName('Maloogaloogaloogaloogalooga')
print(fred.getFullName()) # 'Bob Maloogaloogaloogaloogalooga'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment