Class Implementation in Python

The following demonstrates how to create classes in Python.

class Person:
	"""
	This class represents a Person with fields name and age.
	"""

	# This is the constructor of the class.
	# age here is an optional parameter.
	def __init__ (self, name, age=0):
		self.name = name
		self.age = age

	# Get the name of the person.
	def get_name(self):
		return self.name

	# Get the age of the person.
	def get_age(self):
		return self.age

def main():
	personA = Person('Yancy Vance')
	personB = Person('John Doe', 22)

	print '%s is %d year/s old.' % (personA.get_name(), personA.get_age())
	print '%s is %d year/s old.' % (personB.get_name(), personB.get_age())

main()

The output for this would be:

Yancy Vance is 0 year/s old.
John Doe is 22 year/s old.

One special thing that you have to take note is that, unlike Java and C++, Python does not support method overloading.

Leave a Reply