Python:将类名作为参数传递给函数?

Nea*_*ers 28 python function

class TestSpeedRetrieval(webapp.RequestHandler):
  """
  Test retrieval times of various important records in the BigTable database 
  """
  def get(self):
      commandValidated = True 
      beginTime = time()
      itemList = Subscriber.all().fetch(1000) 

      for item in itemList: 
          pass 
      endTime = time()
      self.response.out.write("<br/>Subscribers count=" + str(len(itemList)) + 
           " Duration=" + duration(beginTime,endTime)) 
Run Code Online (Sandbox Code Playgroud)

如何将上述内容转换为我传递类名称的函数?在上面的示例中,Subscriber(在Subscriber.all(..fetch语句中)是一个类名,这是您使用Python在Google BigTable中定义数据表的方式.

我想做这样的事情:

       TestRetrievalOfClass(Subscriber)  
or     TestRetrievalOfClass("Subscriber")  
Run Code Online (Sandbox Code Playgroud)

谢谢,Neal Walters

Ned*_*der 27

class TestSpeedRetrieval(webapp.RequestHandler):
  """
  Test retrieval times of various important records in the BigTable database 
  """
  def __init__(self, cls):
      self.cls = cls

  def get(self):
      commandValidated = True 
      beginTime = time()
      itemList = self.cls.all().fetch(1000) 

      for item in itemList: 
          pass 
      endTime = time()
      self.response.out.write("<br/>%s count=%d Duration=%s" % (self.cls.__name__, len(itemList), duration(beginTime,endTime))

TestRetrievalOfClass(Subscriber)  
Run Code Online (Sandbox Code Playgroud)

  • 函数,方法,类,模块一切都是python中的第一类对象,你可以传递 (9认同)

Ale*_*lli 12

如果直接传递类对象,就像在"喜欢这个"和"或"之间的代码中那样,可以将其名称作为__name__属性.

从名称开始(如在"或" 之后的代码中)使得检索类对象非常困难(并且不明确),除非您有关于类对象可能包含的位置的指示 - 所以为什么不传递类对象代替?!

  • +1:类是一流的对象——您可以将它们分配给变量和参数以及所有内容。这不是 C++。 (3认同)
  • @NealWalters,如果类在ELSE中定义,而不是在当前模块中的顶级(在函数中,在另一个类中,在另一个模块中,等等),则无法工作,因此通常不是一个好主意. (2认同)