【问题标题】:Python: passing a constant as method parameterPython:将常量作为方法参数传递
【发布时间】:2016-10-26 10:45:11
【问题描述】:

我想将类名作为常量传递给方法。

例子:

def foo(Bar):
   # ...

最后,我希望能够在 foo

方法中使用 Bar 作为类名

这可能吗?

【问题讨论】:

  • 通常不需要将常量作为参数传递给函数。
  • “将类名作为常量传递给方法”是什么意思?也可以通过“在方法 foo 中使用 Bar 作为类名” ?

标签: python parameters constants


【解决方案1】:

是的,您可以将类作为参数传递给函数。下面是一个证明它的例子。

class Bar():
    @staticmethod   # created staticmethod; can be call without creating the object
    def my_print():
        print 'Hello, I am class function'

def foo(my_class):
    my_class().my_print()  # call my_print() of the object passed

foo(Bar) # Pass class "Bar" as argument to "foo()"
# prints: Hello, I am class function

【讨论】:

    【解决方案2】:

    看看这个

    class Bar():
        pass
    
    def foo(param):
        print "class_name is {}".format(param.__name__) #prints class name
    
    foo(Bar)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 2014-02-24
      • 2010-11-16
      • 1970-01-01
      • 1970-01-01
      • 2018-09-09
      相关资源
      最近更新 更多