Python Class Methods

Python Class Methods

Objects can also contain methods. Methods in objects are simply functions that belong to the object.

While properties hold the state (data) of the object, methods define the behavior (actions) of the object.


Creating and Calling a Method

Let us create a method in the Person class, and then execute it on the object.

Class Method Example

// Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

def myfunc(self): print("Hello my name is " + self.name)

p1 = Person("John", 36) p1.myfunc()


Exercise

?

What is a class method in Python?