Published on

cls and self\other in Python

Authors
  • avatar
    Name
    Lif
    Twitter

cls

cls represent the class object itself and allows we to work with class-level variables, call other class method. When referring to class-level attributes and methods within a class method or when we need to manipulate or access attributes or methods that are common to all instances of the class.

cls (class methods):

  • Access and modify class-level attributes.
  • Call other class methods.
  • Perform operations that are related to the class as a whole, not specific to any individual instance.
  • It is necessary to indicate the method is a class method, therefore we must use @classmethod when use cls

Note:

When we use classmethod, it creates a descriptor object that alters the behavior of the method, allowing it to receive the class object (usually referred to as cls) as the first parameter instead of the instance object (self).

self

self represent the instance of the class and allow we to access and manipulate instance variables, call other instance methods.

self

  • Access and modify instance-specific attributes.
  • Call other instance methods.
  • Perform operations that are specific to an individual instance of the class.

other

other represent other object.

Code example

class Person:
    count = 0  # Class-level attribute
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
        Person.count += 1  # Increment class-level attribute
        
    @classmethod
    def get_count(cls):
        return cls.count

# Creating instances of the Person class
person1 = Person("John", 25)
person2 = Person("Jane", 30)

# Accessing class-level attribute using cls
print(Person.get_count())  # Output: 2


# other
class Distance:
    def __init__(self, x=None, y=None) -> None:
        self.ft = x
        self.inch = y
    
    def __ge__(self, other) -> bool:
        total_inches_self = self.ft * 12 + self. inch
        total_inches_other = other.ft * 12 + other.inch
        if total_inches_self >=  total_inches_other:
            return True
        return False
    
    
d1 = Distance(1, 2)
d2 = Distance(4, 10)
print(d1 >= d2)

attention

self, cls, other is just a convention, and you could call it whatever you wanted.

class Person:
    count = 0  # Class-level attribute
    
    def __init_subclass__(this_class):
        this_class.count += 1
    
    @classmethod
    def get_count(klass):
        return klass.count