C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
So: We can call the classmethod example, with the syntax Box.example or on a Box instance "b."
Class: The class argument ("cls" here) can be used as to create a type and return it. Or we can ignore it.
Python program that uses classmethod
class Box:
@classmethod
def example(cls, code):
# This method can be used as an instance or static method.
print("Method called:", code)
# Use classmethod as a static method.
Box.example("cat")
# Use classmethod as an instance method.
b = Box()
b.example("dog")
Output
Method called: cat
Method called: dog
Tip: Static methods can return any value. They can accept any arguments. They are called with the class name, or on an instance.
Also: It makes no difference whether you call a static method with Box.Message or on an instance like b.Message.
Python program that uses staticmethod
class Box:
@staticmethod
def Message(a):
print("Box Message", a)
# Call static method with type.
Box.Message(1)
# Call static method with instance.
b = Box()
b.Message(2)
Output
Box Message 1
Box Message 2