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

后端 未结 5 1375
小蘑菇
小蘑菇 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 14:38

    It a question of namespace pollution. If you have a module with multiple classes and some functions that only make sense for a certain class and its descendents, then make that a static method. The static method can be called either by using the class name or by using an object of the class.

    >>> class A(object):
    ...     @staticmethod
    ...     def static_1():
    ...             print 'i am static'
    ...     def a(self):
    ...             self.static_1()
    ...
    >>> A.static_1()
    i am static
    >>> a=A()
    >>> a.a()
    i am static
    >>> a.static_1()
    i am static
    >>> class B(A):
    ...     pass
    ...
    >>> b=B()
    >>> b.static_1()
    i am static
    >>>
    

提交回复
热议问题