python - 从另一个类更改实例变量
问题描述
我正在尝试self.var_1
从另一个类更改下面的代码,但我收到错误test1 has no attribute 'var_1'
。我觉得我犯了一个简单的错误,但似乎找不到问题所在。
class test1:
def __init__(self):
self.var_1 = "bob"
instance2 = test2()
def change_var(self, new_var):
print(self.var_1) #should print "bob"
self.var_1 = new_var #should change "bob" to "john"
print(self.var_1) #should print "john"
class test2:
def __init__(self):
test1.change_var(test1, "john")
instance = test1()
解决方案
var_1
是一个实例变量,所以需要使用实例:
class test1:
def __init__(self):
self.var_1 = "bob"
instance2 = test2(self) # <<<<<< pass test1 instance
def change_var(self, new_var):
print(self.var_1) #should print "bob"
self.var_1 = new_var #should change "bob" to "john"
print(self.var_1) #should print "john"
class test2:
def __init__(self, t1obj): # <<<< take test1 instance
t1obj.change_var("john") # <<<< use test1 instance
instance = test1()
给出:
bob
john
推荐阅读
- angular - 无法将文件输入到 FileList angular4
- multithreading - Android Studio - AlertDialog 按钮监听器和 ProgressBar 视图
- python-3.x - tkinter 只显示标签文本的顶部
- laravel - Laravel 5.6 签名的 url 在 APP_ENV=production 中不起作用
- json - d3.json() 加载大文件
- java - SpringBoot Ant Matchers 终止于 DefaultSecurityFilterChain [创建过滤器链]
- node.js - 使用 vuejs 时无法在 IE 11 中运行 js 文件
- .net - 使用列表中的任何函数验证输入
- python - 不知道在里面放什么试试……除了……处理不存在的字符串
- c# - Visual Studio 2017 构建包 CLI