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

2024-09-27 04:23:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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)) 

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

我想这样做:

       TestRetrievalOfClass(Subscriber)  
or     TestRetrievalOfClass("Subscriber")  

谢谢, 尼尔·沃尔特斯


Tags: inselftimefetchallwebappclasssubscriber
3条回答

我用的内德密码有点变化。这是一个web应用程序, 因此,我通过URL:http://localhost:8080/TestSpeedRetrieval运行get例程来启动它。我不认为需要初始化。

class TestSpeedRetrieval(webapp.RequestHandler):
  """
  Test retrieval times of various important records in the BigTable database 
  """
  def speedTestForRecordType(self, recordTypeClassname):
      beginTime = time()
      itemList = recordTypeClassname.all().fetch(1000) 
      for item in itemList: 
          pass # just because we almost always loop through the records to put them somewhere 
      endTime = time() 
      self.response.out.write("<br/>%s count=%d Duration=%s" % 
         (recordTypeClassname.__name__, len(itemList), duration(beginTime,endTime)))

  def get(self):

      self.speedTestForRecordType(Subscriber) 
      self.speedTestForRecordType(_AppEngineUtilities_SessionData) 
      self.speedTestForRecordType(CustomLog) 

输出:

Subscriber count=11 Duration=0:2
_AppEngineUtilities_SessionData count=14 Duration=0:1  
CustomLog count=5 Duration=0:2

如果直接传递类对象,如代码中的“like this”和“or”, 您可以将其名称作为__name__属性。

从名称开始(如代码中的“或”之后)会使检索类对象变得非常困难(而且不明确),除非您有一些关于类对象可能包含在哪里的指示——那么为什么不传递类对象呢?!

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)  

相关问题 更多 >

    热门问题