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

33 投票
3 回答
85430 浏览
提问于 2025-04-15 14:22
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")  

谢谢,

尼尔·沃尔特斯

3 个回答

3

这是我使用的Ned代码的一个小改动。因为这是一个网页应用,所以我通过一个网址来启动它:http://localhost:8080/TestSpeedRetrieval。我觉得没有必要使用init这个东西。

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
12

如果你直接传递类对象,就像你代码中“像这样”和“或者”之间那样,你可以通过 __name__ 属性获取它的名字。

从名字开始(就像你代码中“或者”后面那样)会让你很难(而且不太明确)找到类对象,除非你知道这个类对象可能在哪里被包含。那么为什么不直接传递类对象呢?

30

在编程中,有时候我们会遇到一些问题,特别是在使用特定的工具或库时。比如,有人可能在使用某个库的时候,发现它的某个功能不太好用,或者出现了错误。这种时候,大家通常会在网上寻找解决方案,像StackOverflow这样的论坛就是一个很好的地方。在这些论坛上,很多人会分享他们的经验和解决办法,帮助其他人解决类似的问题。

有时候,问题的解决方案可能会涉及到一些代码示例,帮助大家更好地理解如何解决问题。这些代码块通常会用特定的格式标记出来,比如

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)  
,这样大家就能很清楚地看到具体的代码是怎样的。

总之,编程中遇到问题是很正常的,借助社区的力量,我们可以找到很多有用的资源和帮助,让我们的编程之路更加顺利。

撰写回答