Classes in Python

Python is a super-duper cool language, I like it…everybody loves it. It is also popular as the |-|4x0r5 language. It is dynamic and has a clear syntax, most of all fun to use.

But so many books and manuals underplay classes in python that it mostly lives in early programmers as plain scripting language having support for procedures/methods. In reality, Python supports object-oriented programming with classes and multiple inheritance.

Here is an approximate syntactical comparison beween class declaration in C# and python:

C# Version:

public class Person
{
	int Age;
	public string Name;
	float Height;
	float Weight;

	public Person(int age,float height,float weight)
	{
		Age = age;
		Height = height;
		Weight = weight;
		Name = "No Name"
	}

	public void GetInfo()
	{
		system.console.WriteLine("Name: {0}",Name);
		system.console.WriteLine("Weight: {0}",Weight);
		system.console.WriteLine("Height: {0}",Height);
		system.console.WriteLine("Age: {0}",Age);
	}
}

Python Version

class Person:
	Name = "No Name"
	def __init__(self,age,height,weight):
		self.Age = age
		self.Height = height
		self.Weight = weight

	def GetInfo(self):
		print "Name: ", self.Name
		print "Weight: ", self.Weight
		print "Height: ", self.Height
		print "Age: ", self.Age

------------------------------------------------------------------------------------
Usage:

p = Person(20,5.11,70)
p.GetInfo()
print("nn")
p.Name = "Chuck Norris"
p.GetInfo()

------------------------------------------------------------------------------------
Output:
Name:  No Name
Weight:  70
Height:  5.11
Age:  20

Name:  Chuck Norris
Weight:  70
Height:  5.11
Age:  20

Learn more about classes and objects oriented programming in python here

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.