python - should I use static methods or top-level functions

后端 未结 5 1352
小蘑菇
小蘑菇 2020-12-23 14:01

I come from a Java background and I\'m new to python. I have a couple scripts that share some helper functions unique to the application related to reading and writing file

5条回答
  •  隐瞒了意图╮
    2020-12-23 14:51

    One other aspect of Python static methods is that when called on instances, they are polymorphic on the type of the variable they are called on, despite not having an instance of self.

    For example:

    class BaseClass:
        @staticmethod
        def my_method():
            return 0
    
    
    class SubclassLeft:
        @staticmethod
        def my_method():
            return "left"
    
    
    class SubclassRight:
        @staticmethod
        def my_method():
            return "right"
    
    
    instances = [BaseClass(), SubclassLeft(), SubclassRight()]
    
    for i in instances:
        print(i.my_method())
    

    Running this results in

    $ python example.py
    0
    left
    right
    

提交回复
热议问题