python tutorial

Python Class

Learn more about Python, one of the world’s most versatile and popular programming languages.

Python supports Object Oriented Programming (OOP) like many other popular programming languages. OOP revolves around the idea of classes and objects.

A class in Python is a blueprint from which objects can be constructed. Imagine class in OOP as a sketch by an architect for new building construction. Civil Engineers and construction workers then bring this sketch to life by building a real world object i.e. the building in this case.

Naming convention for a Python class is PascalCase. A class can be simply defined as follow in Python:

Code Example
class NewPythonClass:
	'''A docstring like this explains what the class does'''

In the example above, a class in Python can be defined using the class keyword followed by the name of the class. We defined a docstring within the class to explain what the class does and why it is implemented. It helps in providing a detailed explanation about a class.

A class in Python has attributes or properties and methods that act on those attributes. There are also attributes and methods that are pre-built into every Python class and they start with two underscores and end with two underscores __. For example, __init__ is a special method that is used to create new objects from the Python class. __str__ is a special method that is used to provide a string representation of the class when objects are created from it.

Objects are created from a class by calling the constructor function which is __init__ by using the name of the class followed by parentheses (). Any attributes that are needed to create objects from that class will be passed within those parentheses.

Code Example
# python class syntax
>>> class MyPythonClass:
… 	'''this is a docstring to explain what this class does'''
… 	pass

>>> class Shape:
… 	'''This is a base class Shape that allows to create shapes of all kinds'''
… 	def __init__(self):
… 		self.type = 'Shape'
… 	def __str__(self):
… 		return "This is a shape of type {}.".format(self.type)

# create an object from class Shape
# __init__ will be called while creating new objects
>>> shapeObject = Shape()
>>> print(shapeObject)
This is a shape of type Shape.

Learn Python Today

Get hands-on experience writing code with interactive tutorials in our free online learning platform.

  • Free and fun
  • Designed for beginners
  • No downloads or setup required