declaring method inside a class in python code example

Example 1: class methods in python

from datetime import date

# random Person
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def fromBirthYear(cls, name, birthYear):
        return cls(name, date.today().year - birthYear)

    def display(self):
        print(self.name + "'s age is: " + str(self.age))

person = Person('Adam', 19)
person.display()

person1 = Person.fromBirthYear('John',  1985)
person1.display()

Example 2: how to create a class inside a function in python

def create_class():
  class Person:
    def __init__(self, name, age):
      self.name = name
      self.age = age
      
  # returns the class NOT an instance of the class
  # instance would be Person()
  return Person

my_class = create_class()
person1 = my_class("John", 24)

print(f'{person1.name} is {person1.age} years old.')