Torso Torso - 1 month ago 4x
Python Question

Python Class instantiation: What does it mean when a class is called without accompanying arguments?

I am trying to understand some code that I have found on github. Essentially there is a class called "HistoricCSVDataHandler" that has been imported from another module. In the main method this class is passed as a parameter to another class "backtest".

How can a class name that does not represent a instantiated variable be called without raising a NameError.

Or simply put :

Why/How is the class being called as:


Rather than:

CSV_Handler = HistoricCSVDataHandler(foo,bar,etc)

See line 110 for code.



This is a technique called dependency injection. A class is an object just like any other, so there's nothing wrong with passing it as an argument to a function and then calling it inside the function.

Suppose I want to read a string and get either an int or a float back. I could write a function that takes the desired class as an argument:

def convert(s, typ):
    return typ(s)

Calling this gives several possibilities:

>>> convert(3, str)
>>> convert('3', int)
>>> convert('3', float)

So the Backtest function in your code is most likely creating an instance of whichever class you pass - i.e. it is calling HistoricCVSHandler internally to create an instance of that class.

We normally think of Python objects as instances of some class. Classes are similarly objects, and in fact are instances of their so-called metaclass, which by default will be type for classes inheriting from object.

>>> class MyClass(object): pass
>>> type(MyClass)
<type 'type'>