[英]Python: Passing a class name as a parameter to a 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))
如何将以上内容转换为传递类名称的函数? 在上面的示例中,Subscriber(在Subscriber.all()。fetch语句中)是一个类名,这是您使用Python在Google BigTable中定义数据表的方式。
我想做这样的事情:
TestRetrievalOfClass(Subscriber)
or TestRetrievalOfClass("Subscriber")
谢谢,尼尔·沃尔特斯
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)
如果直接传递类对象(如代码中“ like this”和“ or”之间),则可以将其名称作为__name__
属性。
以名称开头(如在代码中“或” 后的名称)会使检索类对象确实非常困难(且不明确),除非您对类对象可能包含的位置有所指示,所以为什么不传递类对象代替?!
我使用的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.