Python Class Example

Python Class

Python being an Object Oriented Programming language, everything in Python is considered to be an object. Each object has its properties and methods.

To define a class in Python, use class keyword as shown below.

class ClassName:
    #class body

Class body can contain definition for properties and methods. These properties and methods are considered members of the class.

Example – Define Class in Python

In the following example, we will define a class with properties and methods.

Python Program

class Laptop:
	name = 'My Laptop'
	processor = 'Intel Core'
	
	@staticmethod
	def start():
		print('Laptop is starting..')
		
	@staticmethod
	def restart(self):
		print('Laptop is restarting')
		
	def details(self):
		print('My laptop name is:', self.name)
		print('It has',self.processor,'processor.')

where

  • name and processor are properties.
  • start(), restart() and details() are methods. Of these start() and restart() are static methods.

Create an Object for Class

Class is a blueprint for objects of that class type. Now, we will create an object for the class we defined in the above code snippet.

Python Program

class Laptop:
	name = 'My Laptop'
	processor = 'Intel Core'
	
	@staticmethod
	def start():
		print('Laptop is starting..')
		
	@staticmethod
	def restart(self):
		print('Laptop is restarting')
		
	def details(self):
		print('My laptop name is:', self.name)
		print('It has',self.processor,'processor.')
		
# Create object
laptop1 = Laptop()
laptop1.name = 'Dell Alienware'
laptop1.processor = 'Intel Core i7'
laptop1.details()
Run Code Copy

We modified some of the class methods to static.

Output

My laptop name is: Dell Alienware
It has Intel Core i7 processor.

Accessing Properties and Methods of Python Class

From the above example, you may have guessed that you can access the properties and methods using dot operator.

object.property
object.method([arguments])

And you can assign the values to properties using assignment operator =.

object.property = somevalue
variable1 = object.propery

Summary

In this tutorial of Python Examples, we learned what a class is, how to define a Python Class with properties and methods, how to create an object for the class, and how to access the properties and methods with the help of well detailed examples.

Related Tutorials

Code copied to clipboard successfully 👍