从 python 中的外部函数访问 class 中的变量

Accessing variable inside class from outside function in python

我需要在某些情况下清除列表,包含列表的变量在 class 函数中。我需要从 class 函数外部访问列表。

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()

我不想使用全局变量,因为我在 class 中使用相同变量名的不同方法。

通过将列表作为参数传递来更新 values

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)

如果满足条件可以抛出异常并在class方法中执行清除

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