Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在同一类的方法之间共享变量_Python_Oop - Fatal编程技术网

Python 在同一类的方法之间共享变量

Python 在同一类的方法之间共享变量,python,oop,Python,Oop,我一直在尝试共享一个在同一类的某个方法中本地声明的变量: class test: def __init__ (self,a,b): self.a=a self.b=b def x(inputList): container = [test(x[0],x[1]) for x in inputList] for i in range (0,2): print("\n")

我一直在尝试共享一个在同一类的某个方法中本地声明的变量:

class test:

    def __init__ (self,a,b):

         self.a=a
         self.b=b

    def x(inputList):

         container = [test(x[0],x[1]) for x in inputList]

         for i in range (0,2):
               print("\n")
               print(container[i].a)
               print(container[i].b)
考虑:

xyz=[["abc","cde"],["fgh","ijk"],["lmn","opq"]]
我运行:

test.x(xyz)
结果是:

abc
cde


fgh
ijk


lmn
opq
这正是我所期望的(列表“container”包含类“test”中的对象)。但是,我希望在类“test”的另一个方法中访问“container”值,例如:

def y():

    rst=container[2].a

    print(rst)
我得到的信息是错误:

NameError: name 'container' is not defined
这方面有什么解决办法吗?可能是某种方法的继承

我尝试使用以下方法:

课堂测试:

def __init__ (self,a,b,container):

    self.a=a
    self.b=b
    self.container=container

def x(inputList):

    container = [test(x[0],x[1]) for x in inputList]

    for i in range (0,3):
        print("\n")
        print(self.container[i].a)
        print(self.container[i].b)
但是,当我尝试跑步时:

test.x(xyz)
我得到:

TypeError: __init__() missing 1 required positional argument: 'container'
我知道我必须改变这段话:

container = [**test(x[0],x[1]**) for x in inputList]

对此有任何猜测吗?

要么将
容器
声明为属性,要么将其作为参数传递给
y()
…在
\uuu init\uuu
方法中继续阅读,执行类似于
self.container=[]
并将
container
的所有用法替换为
self.container
您似乎已经理解了实例属性。只需使用实例属性,或将
容器
返回给调用者。您似乎要求的是
类属性
,而不是任何“全局”(这是最重要的“代码气味”之一)。查找主题并完成包含该语言功能的教程。要么将
容器
声明为属性,要么将其作为参数传递给
y()
…在
\uuu init\uuu
方法中继续阅读,执行类似于
self.container=[]
并将
container
的所有用法替换为
self.container
您似乎已经理解了实例属性。只需使用实例属性,或将
容器
返回给调用者。您似乎要求的是
类属性
,而不是任何“全局”(这是最重要的“代码气味”之一)。查找主题并完成包含该语言功能的教程。