Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How can I turn the above into a function where I pass the name of the class? In the above example, Subscriber (in the Subscriber.all().fetch statement) is a class name, which is how you define data tables in Google BigTable with Python.

I want to do something like this:

       TestRetrievalOfClass(Subscriber)   or     TestRetrievalOfClass("Subscriber")   

Thanks, Neal Walters

like image 967
NealWalters Avatar asked Sep 17 '09 02:09

NealWalters


People also ask

How do you pass a class as a function parameter in Python?

Methods are passed as arguments just like a variable. In this example, we define a class and its objects. We create an object to call the class methods. Now, to call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name.

Can we pass a parameter in a Python function?

Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.


2 Answers

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 image 113
Ned Batchelder Avatar answered Oct 13 '22 23:10

Ned Batchelder


If you pass the class object directly, as in your code between "like this" and "or", you can get its name as the __name__ attribute.

Starting with the name (as in your code after "or") makes it REALLY hard (and not unambiguous) to retrieve the class object unless you have some indication about where the class object may be contained -- so why not pass the class object instead?!

like image 23
Alex Martelli Avatar answered Oct 14 '22 00:10

Alex Martelli