How to define Method in a Class in Python?

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.')
Run Code Copy
  • 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()
Run Code Copy

Output

The developer created a project.
Run Code Copy

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍