python class method cls code example

Example 1: python class

class Person:#set name of class to call it 
  def __init__(self, name, age):#func set ver
    self.name = name#set name
    self.age = age#set age
   

    def myfunc(self):#func inside of class 
      print("Hello my name is " + self.name)# code that the func dose

p1 = Person("barry", 50)# setting a ver fo rthe class 
p1.myfunc() #call the func and whitch ver you want it to be with

Example 2: 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 3: python classmethod

class point:
	def __init__(self, x, y):
    	self.x = x
        self.y = y
        
    @classmethod
    def zero(cls):
    	return cls(0, 0)
        
    def print(self):
    	print(f"x: {self.x}, y: {self.y}")
        
p1 = point(1, 2)
p2 = point().zero()
print(p1.print())
print(p2.print())