【问题标题】:Accessing variable inside class from outside function in python从python中的外部函数访问类内的变量
【发布时间】:2021-09-08 12:26:44
【问题描述】:

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

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

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

【问题讨论】:

  • 你能提供一个更完整的funcsomecondition的例子吗?你能不把条件和对clear的调用添加到类方法中吗?
  • 我已经编辑显示这种情况偶尔会发生一次
  • 我只想在函数内清除类外的列表..
  • values作为参数传递给函数并在函数中执行appendclear
  • func 中引发异常似乎会更干净?然后你就不必在func 中调用clear 并且可以在类方法中调用它

标签: python class methods python-class


【解决方案1】:

通过将列表作为参数传递来更新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 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    • 2016-08-04
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多