Skip to content

Class Implementation in Python

February 10, 2012

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): = name
		self.age = age

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

	# 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())


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.

About these ads

From → Python

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: