Last active
August 29, 2015 14:20
-
-
Save iankronquist/56452f930dcb1ceba3d7 to your computer and use it in GitHub Desktop.
A quick introdution to Python classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is the new style way of declaring classes and should be preferred | |
# Python screwed up the way classes and typing works the first go round, | |
# but they fixed it with new style classes | |
class Object(object): | |
# This is the constructor. It takes an instance of the object and a single argument called foo. | |
def __init__(self, foo): | |
# Make foo a property of this instance | |
self.foo = foo | |
# Add n to foo. Note that if foo is a string, n must also be a string, | |
# or if foo is a numeric type, foo must also be numeric | |
def add(self, n): | |
self.foo += foo | |
#This really doesn't make too much sense in context, but it's an example | |
def __len__(self): | |
return foo | |
o = Object(2) # calls __init__ for you | |
o.add(2) # Equivalent to Object.add(o, 2) | |
print len(o) # calls Object.__len__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment