SwadhyAI Notes

All Python notes

Python Class Methods 🛠️

Object Methods

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

✨ Creating Methods

Let us create a method in the Person class:

python
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()

🔗 The self Parameter

The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.

python
class Person:
  def __init__(mysillyobject, name, age):
    mysillyobject.name = name
    mysillyobject.age = age

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

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

💡 Did You Know?

Python also supports class methods (using @classmethod) which receive the class as the first argument, and static methods (using @staticmethod) which don't receive an implicit first argument.

✨ Pro Tip

Use @staticmethod when you have a method that logically belongs to a class but doesn't need to access any class or instance properties.

python
class MathUtils:
    @staticmethod
    def add(x, y):
        return x + y

print(MathUtils.add(5, 10))