python - 将一个类文件中的变量调用到python3中的另一个文件
问题描述
嗨,我是 python 编程的新手。请帮我解决python3中的这个问题:
包.py
class one:
def test(self):
number = 100 ######I want to access this value and how?
print('test')
class two:
def sample(self):
print('sample')
另一个.py
from pack import *
class three:
def four(self):
obj = one()
print(obj.test())
###### I want to access the number value in this file and i don't know how #######
obj = three()
obj.four()
解决方案
这是一个替代的 pack.py
class One:
def __init__(self):
self.number = 100
def test(self):
print('test')
class Two:
def sample(self):
print('Sample')
另一个.py
from pack import *
class Three:
def four(self):
self.obj = One().number
return self.obj
three = Three().four()
print(three)
通过您的方法,您正在使用类来访问变量。最好在构造函数中实例化变量( 类One中的init方法)。然后导入该类并在另一个文件的另一个类中访问它。
此外,以大写字母开头的类命名也是一个好习惯。还有更多可能的方法,但希望它有所帮助。
推荐阅读
- python - ReportLab 中的镜像边距
- reactjs - Instagram Oauth - 允许用户选择使用哪个帐户登录?
- pandas - 一次替换熊猫列中的多个值
- python - 如何创建一个不被 3 整除的 5 个下一个数字的列表
- python - 硒驱动程序中的错误 = webdriver.firefox()
- node.js - 如何将多部分文件上传直接发送到节点中的mongodb
- ios - 将 Xcode 更新到 12.5 和 iOS 更新到 14.5 后,React Native 0.64 不会构建 iOS 应用程序
- html - 在 flexbox 中制作第二个 div 不能超过第一个 div 的高度
- node.js - 无法通过 Node 从 http 服务器请求
- php - php将变量放入从数组加载的字符串中