Python is an object-oriented programming language ideally designed for rapid prototyping of complex applications. Like Perl, Python source code is also available under the GNU General Public License (GPL).

In this article we will see about Python Class & Objects: Define Class, Instances and Inheritance with example.

1) Define a class in Python

In Python, classes are defined by the "Class" keyword, inside classes, one can define functions or methods that are part of the class:
class myClass():
	def name(self):
		print 'Apple'
	def color(self):
		print 'Red'

2) Make an object of the class in Python

Objects of a class can be created as shown below:
obj = myClass()

3) Call a method in a class in Python

Methods can be called upon class's object as shown below:
obj.name()
obj.color()

4) Complete example, python class, object and method calling

class myClass():
	def name(self):
		print 'Apple'
	def color(self):
		print 'Red'

obj = myClass()
obj.name()
obj.color()

Output: Output will be something like this:

Apple
Red


5) Inheritance in Python

Inheritance refers to defining a new class with less or no modification to an existing class. The new class is called derived class and from one which it inherits is called the base.
class myClass():
	def name(self):
		print 'Apple'
	def color(self):
		print 'Red'

class myChildClass(myClass):
	def color(self):
		print 'Red from child'


def main():
	obj = myChildClass()
	obj.name()
	obj.color()

if __name__== "__main__":
  main()


Output: Output will be something like this:

Apple
Red from child


In this article we have seen, Python Class & Objects: Define Class, Instances and Inheritance with Examples. In upcoming articles we will see more complex usecases and tricks of python.
  • By Techburps.com
  • Sep 30, 2017
  • Python