Python Class instantiation: What does it mean when a class is called without accompanying arguments?
<p>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". </p>

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

<p>Or simply put :</p>

<p>Why/How is the class being called as:</p>

<pre><code>Backtest(HistoricCSVDataHandler)
</code></pre>

<p>Rather than:</p>

<pre><code>CSV_Handler = HistoricCSVDataHandler(foo,bar,etc)
Backtest(CSV_Handler)
</code></pre>

<p><a href="https://github.com/djunh1/event-driven-backtesting/blob/master/snp_forecast.py" rel="nofollow">See line 110 for code.</a></p>

<p>Regards</p>

<p>This is a technique called <a href="https://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow"><em>dependency injection</em></a>. 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.</p>

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

<pre><code>def convert(s, typ):
    return typ(s)
</code></pre>

<p>Calling this gives several possibilities:</p>

<pre><code>&gt;&gt;&gt; convert(3, str)
'3'
&gt;&gt;&gt; convert('3', int)
3
&gt;&gt;&gt; convert('3', float)
3.0
</code></pre>

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

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

<pre><code>&gt;&gt;&gt; class MyClass(object): pass
... 
&gt;&gt;&gt; type(MyClass)
&lt;type 'type'&gt;
</code></pre>

python class