Reputation:
I am trying to define an object variable of a class so that it would be a tuple as seen below:
class MyClass(object):
def __init__(self):
self.results = ? # tuple
def generate_results(self, a):
# tuple to hold the 3 result integers
self.results = (self.calculate_first_result(a),
self.calculate_second_result(a),
self.calculate_third_result(a))
(where the calculate_first_result
, calculate_second_result
and calculate_third_result
are static methods of MyClass
which perform some calculations and return an int
)
I do not understand how the self.results
in __init__
should be defined in order for it to hold the tuple with the 3 integers as it is calculated in generate_results
method.
I am new with the class and object variable concepts in Python so any shortcomings in my design and approach will be appreciated.
Upvotes: 0
Views: 5963
Reputation: 22754
You can optionally code this:
def __init__(self):
self.results = ()
If I judge just from your code, I may say it is not important because inside generate_results()
you overrided self.results
.
It can be useful to initialize the empty tuple only if you need to keep a trace of it for further needs in your program, otherwise not.
The following code summerizes what I said:
class Begueradj:
def __init__(self):
self.results = ()
def generate_results(self):
self.results = (1,2,3)
print ' inside generate_results(): '+str(self.results)
def display(self):
print ' inside display(): '+str(self.results)
# Main program starts here
if __name__ =='__main__':
b = Begueradj()
b.display() # This line will not work if you do not run self.results = () inside __init__()
b.generate_results()
b.display()
If you do not need to keep a track of self.results, meaning in our code sample that you do not need to call display()
just before generate_results()
method, then this will lead us to what @juanpa.arrivillaga commented you: I mean, it will become useless to initialize the empty tuple. The code below reflects this situation:
class Begueradj:
def __init__(self):
# Do not do anything
# We do not need to keep a track of self.results
pass
def generate_results(self):
self.results = (1,2,3)
print ' inside generate_results(): '+str(self.results)
def display(self):
print ' inside display(): '+str(self.results)
# Main program starts here
if __name__ =='__main__':
b = Begueradj()
# b.display() you can no longer call display() here as we did not initialize self.results inside __init__
b.generate_results()
b.display()
Upvotes: 1