How to define Method in a Class?


Python - Define a method in a class

Python Class can contain multiple methods. To define a method in Python Class, you can use def keyword and function syntax.

Example

class Developer:
  def createProject(self):
    print('The developer created a project.')
  • We have created a method named createProject.
  • This method does not accept any arguments. self is the default argument that has to be provided in the definition.
  • There is only a single statement in the method. However, you can add more statements.
  • The function does not return any value.

Calling the method

You can call the method using class object.

class Developer:
  hoursperday = 8
  
  def createProject(self):
    print('The developer created a project.')
	
#create object
dev1 = Developer()

#call object's method
dev1.createProject()

Output

The developer created a project.

Summary

In this Python Classes and Objects tutorial, we learned how to define a method in a class.