Thursday, December 12, 2013

Python Classes

As I struggled to better understand Python classes, I took a few notes from the research I did and created this example class. Hopefully this will provide some insight for those who are new to Python as well. Please post any questions or comments.
#Classes begin with the word 'class' followed by the class name class identity: # Statements or functions follow, referred to as methods. # Method attributes always start with 'self' # 'self' is a temporary placeholder for the object # The value of the attribute 'first' is passed into the method def createFirst(self,first): # The object's value for 'first' will be assigned based on the input self.first = first def createLast(self,last): self.last=last # The objects assigned value of 'first' is returned def displayFirstname(self): return self.first def displayFullname(self): return self.first + " " + self.last def saying(self): print "Hello %s %s " % (self.first, self.last)
Once your class is created you can start to create objects that use the methods within the class.
# Associate object with class
user=identity()
# Use methods to assign values
user.createFirst('Bill')
user.createLast('Jones')
# Retrieve properties of an object
user.displayFullname()
'Bill Jones'
# Create another object that uses all the same methods of the class
user2=identity()
# If you ever forget what methods are available:
dir(user)

No comments:

Post a Comment