python - 如何在类的方法内、类外访问变量、列表或字典?
问题描述
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()
怎么访问a
,ar
和dict_t
外面的类?我想在a
这里打印ar
。谢谢你。
解决方案
像这样:
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
推荐阅读
- openmdao - 有什么方法可以即时更新稀疏部分索引
- flutter - 如何开始我的 Dart & Flutter 之旅?
- r - 如何避免 R 中箱线图的标签/文本重叠?
- oracle - 使用“新”和“旧”值依赖关系重构 Oracle 触发器中的子句
- three.js - Three.js R105 - intersectObjects 不是函数,碰撞工作者
- python - 使用用户输入从类中调用函数
- neo4j - 是否有任何 Cypher 查询用于返回节点的所有属性但不包括特定属性?
- reactjs - 在 React 组件之间切换,在状态与 React 路由器之间切换
- python - sklearn,ValueError:即使我没有使用字符串,也无法将字符串转换为浮点数
- git - Git 在询问凭据时不允许我添加我的 github 密码