I have a class -
class Start(object):
def __init__(self):
self.flag = False
self.my_list = []
def set_up(self):
self.flag = True
def end_set_up(self):
self.my_list = [i*2 for i in self.my_list]
And another class which inherits from this class -
class Process(Start):
def __init__(self):
super(Process, self).__init__()
def check_flag(self):
if self.flag:
self.my_list = range(1, 10)
And in the third class, I want to do some operations on my_list
class Operation(Start):
def __init__(self):
super(Operation, self).__init__()
def perform_op(self):
self.my_list = [i*2 for i in self.my_list]
Now these classes are used in a code snippet as -
start_ob = Start()
start_ob.set_up()
process_ob = Process()
process_ob.check_flag()
op_ob = Operation()
op_ob.perform_op()
My understanding of classes is not that strong. What I thought of achieving with this was -
- Set up class
Start() - Inherit flag from class
Start()intoProcess()which should beTruenow since I calledset_up()function herestart_ob.set_up() - Set
my_listin base class to be[1,2....9] - Inherit
Start()intoOperation()and modify list[1,2....9]that I created in the objectProcess()
But things are not moving according to my understanding. my_list is empty as set_up is False for classes Process and Operation. How do I change my code to make it work according to what my understanding is?
Edit- In the base class, there are two methods, one has to run when the object is initialised, right at the beginning. It will set a flag to True. After which another method in the same base class needs to run according to that flag
1 Answer 1
What you’re doing here:
start_ob = Start()
start_ob.set_up()
process_ob = Process()
process_ob.check_flag()
op_ob = Operation()
op_ob.perform_op()
... is creating three entirely separate objects. Each one has its own my_list. Just like you can have three different int objects and they’re all separate values, you can have three different Start objects and they’re all separate values.
What you probably wanted is:
ob = Operation()
ob.set_up()
ob.check_flag()
ob.perform_op()
Now you have a single object, which is an Operation, and therefore a Process, and therefore a Start, so you can call methods from any of those three types and they will affect your object’s value. And now you’re using inheritance.
3 Comments
Operation isn't inheriting from Process, they are sister classes. It won't have check_flagcheck_flag from Operation class as check_flag is a function of Process not Operation?
self.flag = True?