首页 > 解决方案 > 如何在类的方法内、类外访问变量、列表或字典?

问题描述

class test:

    def __init__(self):

        print('inside the code')

    def add(self,x,y):

        a=x+y

    def list_test(self):

        ar=[]
        ar.append(1)
        ar.append(2)


    def dict_test(self):
        dict_t={1:2,2:3}

cl=test()

怎么访问aardict_t外面的类?我想在a这里打印ar。谢谢你。

标签: pythonclassmethods

解决方案


像这样:

class test:
    def __init__(self):
        self.ar = []
        self.dict_t = {}
        self.a = 0
        print('inside the code')

    def add(self, x, y):
        self.a = x+y

    def list_test(self):
        self.ar.append(1)
        self.ar.append(2)

    def dict_test(self):
        self.dict_t = {1: 2, 2: 3}


t = test()
t.list_test()
print(t.ar)
t.add()
print(t.a)

笔记:

在启动函数中定义变量。然后您可以通过以下方式访问它们:

class_name.var_name

推荐阅读