【问题标题】:Access a list that is inside a function that is inside a class访问在类内的函数内的列表
【发布时间】:2020-03-24 13:21:40
【问题描述】:

假设我在a.py 文件中有这样一个类:

class MyClass():
    def get(self, request, format='json'):
        pipeline = ['something_here']

如何从b.py 等另一个文件访问列表pipeline
a.pyb.py 位于同一目录中。

我正在尝试这样的事情:

from a import MyClass

my_list = MyClass.pipeline

OBS.:我无法更改 a.py 文件,因为其他人正在使用它。

【问题讨论】:

  • 列表管道仅在方法执行期间存在,在此之前它没有创建,之后它超出范围。如果您需要访问此列表,请考虑将其作为您的类或类实例的属性。
  • 可以添加pipeline作为函数成员,见here

标签: python class


【解决方案1】:

您无法直接访问它。您可以做的是将它返回,将其作为实例的attribute 接收,或者将其设为global 类变量。

【讨论】:

    【解决方案2】:

    由于您无法更改a.py,因此无法访问此列表。该列表需要声明为MyClass 的数据成员,或者需要从MyClass.get() 返回。否则是不可能的

    【讨论】:

    • 我怎样才能将此列表声明为MyClass的数据成员?
    • 改成self.pipeline = ['something_here']
    【解决方案3】:

    解决这个问题的一种方法是使用继承,只需在新类中更改MyClass 的逻辑即可。

    鉴于a.py的以下内容:

    class MyClass:
        def __init__(self, x,y,z):
            self.x = x
            self.y = y
            self.z = z
    
        def get(self, somestring):
            pipeline = [somestring]
            return pipeline
    

    创建MyClass 的新对象并调用get("somestring"),将返回一个仅包含该字符串的列表。但是,我们没有在类内部设置属性,所以它只能在方法本身内部使用。

    创建一个新文件,在本例中为b.py,我们可以创建一个新类,继承自第一个类,只需修改get 方法以获得我们想要的逻辑。

    from a import MyClass
    
    class MyNewClass(MyClass):
        def get(self, somestring):
            self.pipeline = [somestring]
    

    b.py 内部,我们可以进行以下测试:

    old = MyClass(1,2,3)
    print(old.x, old.y, old.z)
    print(old.get("this is the input-string"))
    
    new = MyNewClass(4,5,6)
    print(new.x, new.y, new.z)
    new.get("This is the second input-string")
    print(new.pipeline)
    

    输出:

    1 2 3
    ['this is the input-string']
    4 5 6
    ['This is the second input-string']
    

    【讨论】:

      猜你喜欢
      • 2017-11-11
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 2018-07-26
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多