Assign Global Variable Inside Class From Class Variable
<p>I have a question about classes in Python. I have create a class that looks something like this:</p>

<pre><code>class Model(Object):

    __table__ = 'table_name'

    def func():

    def func2():
</code></pre>

<p>The table name is a global variable that the functions feed off of. I am trying to add old data so I would like to change the table name depending on if I am filling in from old information, so this is what I tried. </p>

<pre><code>class Model(Object):

    def __init__(self, backfill = False):
         self.backfill = backfill

    if self.backfill:
         __table__ = 'table_name'
    else:
         __table__ = 'table_name2'

    def func():

    def func2():
</code></pre>

<p>The final call would be something like this:</p>

<pre><code>if backfill:
     model = Model(True).func()
else:
     model = Model.func()
</code></pre>

<p>Then I realized this wouldn't work because I cannot call self.backfill from outside the class definitions. I even tried creating a definition and calling that inside the class but that did not work either.</p>

<p>My question is:</p>

<ol>
<li>Is there a way to initialize the global variable inside the class from the class variables? Or is there a better way to do this in general?</li>
</ol>

<p><code>__table__</code> is a class variabe, which means you can access it from an instance or from the class itself. You can update any instance value according to the value of <code>backfill</code> in the <code>__init__</code> method:</p>

<pre><code>class Model(Object):
    __table__ = 'table_name'
    def __init__(self, backfill = False):
        self.backfill = backfill
        if self.backfill:
            self.__table__ = 'table_name2'
</code></pre>

<p>Then to create an instance, just give the <code>backfill</code> parameter to the constructor, without any if/else statement:</p>

<pre><code>print(Model.__table__)
# table_name
backfill = True
model = Model(backfill)
print(model.__table__)
# table_name2
</code></pre>

<p>But I don't see the point of using a class variable in your case. You can just define it in the <code>__init__</code> method:</p>

<pre><code>class Model(Object):
    def __init__(self, backfill = False):
        self.backfill = backfill
        self.__table__ = 'table_name'
        if self.backfill:
            self.__table__ = 'table_name2'
</code></pre>

python python-2.7 class