python - passing variables across methods and classes

2330 views python
2

I have some code that generically resembles the following:

class ABC(Parent):
    def func1(self, **kwargs)
        start_time = time.time()
        ...
        ...
    return stuff

class XYZ(Parent):
    def func2(self, **kwargs)
        ...
        ...
        a = time.time() - start_time           
    return other_stuff

I'm looking for the absolute simplest way to use the variable start_time defined in func1 of class ABC inside of func2 within class XYZ.

Note: This code is very generic and the actual code I'm working with is much, much more complicated. Other answers I've found have mentioned defining start_time outside of either class and then passing them in, OR they involve changing arguments. I cannot do this. My start_time needs to be defined exactly here and nowhere else, and I cannot change my arguments for either func1 or func2.

Thanks for any assistance.

answered question

your arguments are **kwargs, you can pass anything.

You have to pass the instance of ABC to the instance of XYZ.

@Daniel what is the syntax for this? I'm very new to Python.

2 Answers

0

You can make start_time a class attribute in Parent.

class Parent(object):
    def __init__(self):
        self.start_time = None

class ABC(Parent):
    def func1(self, **kwargs)
        self.start_time = time.time()
        ...
        ...
    return stuff

class XYZ(Parent):
    def func2(self, **kwargs)
        ...
        ...
        a = time.time() - self.start_time           
    return other_stuff

posted this
8

It's difficult to solve your problem in a method that isn't going to be messy. Essentially, you will need to use a variable outside both of your functions. I think your best option is to use python's global keyword:

class ABC(Parent):
    def func1(self, **kwargs):
        global start_time
        start_time = time.time()

        return stuff

class XYZ(Parent):
    def func2(self, **kwargs):
        global start_time
        a = time.time() - start_time

        return other_stuff

posted this

Have an answer?

JD

Please login first before posting an answer.