Reputation: 846
I have a question about classes in Python. I have create a class that looks something like this:
class Model(Object):
__table__ = 'table_name'
def func():
def func2():
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.
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():
The final call would be something like this:
if backfill:
model = Model(True).func()
else:
model = Model.func()
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.
My question is:
Upvotes: 1
Views: 1554
Reputation: 3775
__table__
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 backfill
in the __init__
method:
class Model(Object):
__table__ = 'table_name'
def __init__(self, backfill = False):
self.backfill = backfill
if self.backfill:
self.__table__ = 'table_name2'
Then to create an instance, just give the backfill
parameter to the constructor, without any if/else statement:
print(Model.__table__)
# table_name
backfill = True
model = Model(backfill)
print(model.__table__)
# table_name2
But I don't see the point of using a class variable in your case. You can just define it in the __init__
method:
class Model(Object):
def __init__(self, backfill = False):
self.backfill = backfill
self.__table__ = 'table_name'
if self.backfill:
self.__table__ = 'table_name2'
Upvotes: 2