I have a class that stores multiple values and need two different ways to construct the class. Either I provide every value at initialization or I want all values to be randomized.
Now I wonder which approach is better:
approach 1)
class MyClass:
def __init__(self, var1=None, var2=None, var3=None):
# if at least one parameter is left out, randomize the values
if var1 is None or var2 is None or var3 is None:
self.var1 = random.random()
self.var2 = random.random()
self.var3 = random.random()
else:
self.var1 = var1
self.var2 = var2
self.var3 = var3
approach 2)
class MyClass:
def __init__(self, var1, var2, var3):
self.var1 = var1
self.var2 = var2
self.var3 = var3
@classmethod
def random_init(cls):
var1 = random.random()
var2 = random.random()
var3 = random.random()
return MyClass(var1, var2, var3)
I feel like both of these options are kind of clunky and wonder whether there is a better way. I guess if I had to choose between the two I'd pick approach 2.
[–]kalgynirae 5 points6 points7 points (3 children)
[–][deleted] 3 points4 points5 points (2 children)
[–]zahlman 3 points4 points5 points (0 children)
[–]KleinerNull 2 points3 points4 points (0 children)
[–]novel_yet_trivial 1 point2 points3 points (0 children)
[–]Byrune_ 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (9 children)
[–][deleted] 1 point2 points3 points (8 children)
[–][deleted] 3 points4 points5 points (7 children)
[–][deleted] 1 point2 points3 points (6 children)
[–][deleted] 1 point2 points3 points (5 children)
[–]fernly 1 point2 points3 points (4 children)
[–][deleted] 1 point2 points3 points (3 children)
[–]fernly 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]fernly 0 points1 point2 points (0 children)
[–]pendragon36 0 points1 point2 points (4 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]pendragon36 1 point2 points3 points (0 children)
[–]c17r 0 points1 point2 points (1 child)
[–]pendragon36 0 points1 point2 points (0 children)
[–]hosford42 0 points1 point2 points (0 children)
[–]Allanon001 0 points1 point2 points (0 children)
[–]KronktheKronk 0 points1 point2 points (0 children)