Vivek Kumar Singh
Vivek Kumar Singh

Reputation: 3350

Call a variable in one function from another function inside a class

I am following this answer and trying to call a variable of one function from another function, but getting an error. Below is my test code.

import datetime
from datetime import timedelta
import time

class TimeTesting:
    def TimeTest1(self):
        T1 = datetime.datetime.now()
        time.sleep(5)
        print('TimeTest1 is being called')

    def TimeTest2(self):
        T2 = datetime.datetime.now()
        TimeDiff = T2 - self.T1
        print('Timetest2 has been called')
        print('Time diff is {}'.format(TimeDiff))

ob = TimeTesting()
ob.TimeTest1()
ob.TimeTest2()

Below is the error that I am getting -

TimeDiff = T2 - self.T1 AttributeError: 'TimeTesting' object has no attribute 'T1'

Can someone point me out what I am doing wrong?

Upvotes: 0

Views: 71

Answers (1)

Philippe
Philippe

Reputation: 181

You would need to define T1 as an instance variable:

self.T1 = datetime.datetime.now()

As it stands, T1 is just a local variable to method TimeTest1, and is only in scope in that method.

Upvotes: 3

Related Questions