Explanation of a decorator class in python

后端 未结 2 1419
无人共我
无人共我 2021-02-06 17:50

While reading up about some python module I encountered this decorator class:

# this decorator lets me use methods as both static and instance methods
class omni         


        
2条回答
  •  太阳男子
    2021-02-06 17:57

    omnimethod does what it says in the comment; it will let you call some_function as either a 'static function' on a class or as a function on an instance of the class. @property is a standard decorator (see the python docs) that exposes a function in a way that makes it look like a simple instance variable.

    class B:
      @omnimethod
      def test(self):
        print 1
    
      @property
      def prop(self):
        return 2
    
    >>> b = B()
    >>> b.test()
    1
    >>> B.test()
    1
    >>> b.prop
    2
    

提交回复
热议问题