Static methods in Python?

后端 未结 10 757
悲&欢浪女
悲&欢浪女 2020-11-22 02:36

Is it possible to have static methods in Python which I could call without initializing a class, like:

ClassName.static_method()
10条回答
  •  心在旅途
    2020-11-22 02:44

    Perhaps the simplest option is just to put those functions outside of the class:

    class Dog(object):
        def __init__(self, name):
            self.name = name
    
        def bark(self):
            if self.name == "Doggy":
                return barking_sound()
            else:
                return "yip yip"
    
    def barking_sound():
        return "woof woof"
    

    Using this method, functions which modify or use internal object state (have side effects) can be kept in the class, and the reusable utility functions can be moved outside.

    Let's say this file is called dogs.py. To use these, you'd call dogs.barking_sound() instead of dogs.Dog.barking_sound.

    If you really need a static method to be part of the class, you can use the staticmethod decorator.

提交回复
热议问题