Search code examples
pythonclassmethodspython-class

Accessing variable inside class from outside function in python


I need to clear the list in certain conditions and the variable containing the list is inside the class function. I need to access the list from outside the class function.

Class A:
   def insideclass(self):
       values=[]
       for i in range(10):
           values.append(func())

def func():
    if datetime.time.now()=="2021-06-25 10:15:52.889564":
       values.clear()
return datetime.time.now()


classvariable=A()
classvariable.insideclass()

I don't want to use a global variable because I have different methods inside the class with the same variable name.


Solution

  • Updating values by passing the list as an argument:

    class A:
       def insideclass(self):
           values=[]
           for i in range(10):
               func(values)
    
    def func(values):
        now = datetime.time.now()
        if now == "2021-06-25 10:15:52.889564":
            # You can't compare a datetime to a string...
            values.clear()
        values.append(now)
    

    You could throw an exception if the condition is met and perform the clear in the class method

    class A:
       def insideclass(self):
           values=[]
           for i in range(10):
               try:
                   values.append(func())
               except:
                   values.clear()
    
    def func():
        now = datetime.time.now()
        if now == "2021-06-25 10:15:52.889564":
            raise Exception('This should be a more specific error')
        else:
            return now