代码之家  ›  专栏  ›  技术社区  ›  Jesse Shieh José Valim

可以将类(不是对象)作为参数传递给Python中的方法吗?

  •  6
  • Jesse Shieh José Valim  · 技术社区  · 16 年前

    我想做如下的事情

    class A:
      def static_method_A():
        print "hello"
    
    def main(param=A):
      param.static_method_A()
    

    我想这个相当于 A.static_method() . 这有可能吗?

    3 回复  |  直到 9 年前
        1
  •  8
  •   C. K. Young    16 年前

    当然。类是Python中的第一类对象。

    但是,在您的示例中,您应该使用 @classmethod (类对象作为初始参数)或 @staticmethod (没有初始参数)方法的修饰器。

        2
  •  5
  •   Greg Hewgill    16 年前

    您应该能够执行以下操作(请注意 @staticmethod 装饰师):

    class A:
      @staticmethod
      def static_method_A():
        print "hello"
    def main(param=A):
      param.static_method_A()
    
        3
  •  0
  •   Unknown    16 年前

    当然,为什么不呢?不要忘记将@staticmethod添加到静态方法中。

    class A:
      @staticmethod
      def static_method_A():
        print "hello"
    
    def main(param=A):
      param.static_method_A()