2009-09-17 100 views
24
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中的数据表。Python:将类名作为参数传递给函数?

我想做的事情是这样的:如果直接传递类对象,如与代码“像这样”和“

 TestRetrievalOfClass(Subscriber) 
or  TestRetrievalOfClass("Subscriber") 

感谢, 尼尔·沃尔特斯

回答

17
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) 
+0

酷,我不知道,你可以通过一类,就像任何其他变量。我错过了那个连接。 – NealWalters 2009-09-17 03:37:11

+7

函数,方法,类,模块所有东西都是python中的第一个类对象,你可以通过 – 2009-09-17 05:31:27

10

或“, 您可以获得其名称__name__属性。

从名称开始(如代码之后“或”)使得检索类对象非常困难(并且不是明确的),除非您有关于类对象可以包含在哪里的一些说明 - 所以为什么不传递类对象?!

+1

+1:类是第一类对象 - 你可以将它们分配给变量和参数以及其他所有东西。这不是C++。 – 2009-09-17 12:05:37

+0

OBJ = globals()[className]()其中className是包含类名称字符串的变量。从一个旧的帖子得到了这里:http://www.python-forum.org/pythonforum/viewtopic.php?f=3&t=13106 – NealWalters 2009-09-17 18:44:39

+1

@NealWalters,如果该类定义在任何地方,而不是在顶部当前模块中的级别(在函数中,在另一个类中,在另一个模块中,等等),所以通常不是一个好主意。 – 2009-09-18 03:46:33

1

我使用的Ned代码略有差异。这是一个web应用程序, ,所以我通过一个URL运行get例程来启动它: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 
相关问题