Static Methods - Tutorial

Static Methods - Tutorial

·

1 min read

What are static methods?

Static Methods are methods that are not limited to a class, but at the same time cannot directly access other class functions(methods) or variables. Since they are not associated with an instance, They can be very flexible. But I'll talk about the flexibility later, and just focus on how to create static methods and call them.

Similar to Class methods

Remember, to create a class method you first need to state @classmethod before you define the method. It's just like that. In order to create a static method, you need to state @staticmethod before you define the method. Here's an example:

class Vector():
    @staticmethod
    def static(n):
        print('you've entered: %n' % (n))


# Call
print(Vector.static(2))

Very simple. Right? So now, when you need to write a static method, all you do is to @staticmethod before you define the method. And always remember, they CANNOT access class variables!

Happy Coding!