2009-09-17 304 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 
相關問題