Continuing the discussion from Python should introduce the concept of variable declaration to prevent potential issues that may arise from variable redefinition. :
Hi all, I’m new here and I have a little question when I take up writing my own classes. The biggest problem is about class initialization. Python mixes declaration with assignment, so I’m not sure whether I should do this:
class myclass:
def __init__(self, object_):
# declaration
self.__var = None
# assignment
self.__update_var(object_)
def __update_var(self, item):
# some code
self.__var = something
Or,
class myclass:
def __init__(self, object_):
# declaration and assignment
self.__var = self.__get(object_)
def __get(self, item):
# some code
return item
Neither of these seem proper. In the first case, this seems redundant to refer to var twice. And all of the update functions have side effects, which means they cannot be easily reused out of the class. In the second case, if I need to update __var in another function, I need to manually do self.__var = self.__get(var) again. This seems tiresome when I have coupled variables:
class myclass:
def __init__(self, object_):
# declaration and assignment
self.__varA = __get(object_)
self.__varB = __get(self.__varA)
self.__varC = __get(self.__varB)
def __get(self, item):
# some code
return item
def calc_then_reset(self, another_obj, options):
# If I change self.__varA here,
# I need to manually update all of the consequential variables.
Neither can I change the order of clauses when declaring. (Sometimes I want __varA and __varC to be public while __varB private, and it is impossible to put all private variables in one region and public ones in another.) Nor could I make it clear like this:
class myclass:
def __init__(self, object_):
# declaration and assignment
self.__varA = None
self.__varB = None
self.__varC = None
self.__updateA(init_value)
def calc_then_reset(self, another_obj, options):
results = xxx
self.__updateA(results)
def __updateA(self, results)
self.__varA = xxx
__updateB(self.__varA)
def __updateB(self, varA)
self.__varB = xxx
__updateC(self.__varB)
def __updateC(self, varB)
self.__varC = xxx
So could I ask for the best practice to do this? Thank you all!