Understand Function without Self in Python Class – Python Tutorial

By | February 27, 2024

A function without self parameter in python class may be a @classmethod ,@staticmethod or normal method. Here is the tutorial:

Understand Python @classmethod and @staticmethod with Examples: A Beginner Guide – Python Tutorial

It is easy to understand python @classmethod and @staticmethod function. How about a normal function?

For example:

class T:
    def __int__(self, id = 0):
        self.id = id
    def from_pretrain( device="cpu"):
        print(device)

Here from_pretrain() function does not contain self parameter in class T and it is not @classmethod and @staticmethod.

How to call function without self in python class?

As example above, we can call from_pretrain() by class name.

For example:

T.from_pretrain()

Here T is the class name.

Run this code, we will see:

cpu

Can we use self attribution in function without self parameter?

The answer is: No

Can we use self attribution in function without self parameter?

Here self.id is class T instance attribution, we can not use it in from_pretrain() function.

Can we use class attribution in function without self parameter?

The answer is: yes

For example:

class T:
    x = 3
    def __int__(self, id = 0):
        self.id = id
    def from_pretrain( device="cpu"):
        T.x = 2 * T.x
        y = T.x
        print(device)
        return y

x = T.from_pretrain()
print(x)

Here variable x is T class attribution. Run this code, we will see:

cpu
6