Ask Your Question
3

Is it possible for a function within a class to operate without the use of the self parameter?

asked 2022-02-04 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-01-29 23:00:00 +0000

david gravatar image

Yes, it is possible for a function within a class to operate without the use of the self parameter if the function does not need to access or modify any instance variables. Such functions are called static methods and do not have access to the instance or the class itself. They are defined using the @staticmethod decorator. For example:

class MyClass:
    @staticmethod
    def my_static_method(a, b):
        return a + b

In the above example, the my_static_method function does not have the self parameter and can be called directly on the class without creating an instance of the class. For example:

result = MyClass.my_static_method(2, 3)
print(result) # Output: 5
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-04 11:00:00 +0000

Seen: 9 times

Last updated: Jan 29 '22