Issue
What is the easiest way to define a class with 40 or more variables in Python?
Python 3.8 on Windows 10 is used.
class ExampleClass:
def __init__(self, val_1 , val_2, .....40 variables):
self.val_1 = val_1
self.val_2 = val_2
.
.
40 variables
.
self.val_40 = val_40
def example_function(self):
#function code
Solution
Well, just type in their defaults in the class __init__
as usual. You'll be typing these variable names throughout the program (otherwise, why are they there?) so its not much more work to do it. Sometimes lists and dictionaries are better choices, but there's no way we'd know for this case.
After your update showing 40 variables in __init__
, you could allow any number of variables on init, make sure it meets your criteria (here I require exactly 40) and put them in a list.
class ExampleClass:
def __init__(self, *vals):
"""Example(val1, ... val40)"""
if len(vals) != 40:
raise ValueError(f"Need 40 variables, got {len(vals)}")
self.vals = list(vals)
def example_function(self):
# now using val_1 is
print(self.vals[0])
The thing about variables named "val_0" to "val_40" is that it really sounds listish. But whether a list is a good idea depends on how you want to use them later. If you really want to address them individually as somevariable.val_0
, etc... then your existing example is the best way to do it.
Answered By - tdelaney
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.