如何把一个python文件中的数据导入到另一个python文件的class中进行使用举例说明
时间: 2023-12-10 18:41:50 浏览: 238
假设我们有两个python文件,一个是`data.py`,其中定义了一个列表:
```python
# data.py
my_list = [1, 2, 3, 4, 5]
```
另一个是`class.py`,其中定义了一个类`MyClass`,我们想要在这个类中使用`data.py`中的`my_list`:
```python
# class.py
from data import my_list
class MyClass:
def __init__(self):
self.data = my_list
def print_data(self):
print(self.data)
```
在`class.py`文件中,我们使用`from data import my_list`来导入`data.py`中的`my_list`。然后在`MyClass`类的构造函数`__init__`中,我们将`my_list`赋值给`self.data`,这样就可以在类的其他方法中使用了。
现在我们可以在另一个python文件中使用`MyClass`了:
```python
# main.py
from class import MyClass
my_obj = MyClass()
my_obj.print_data() # 输出 [1, 2, 3, 4, 5]
```
在`main.py`文件中,我们使用`from class import MyClass`来导入`class.py`中的`MyClass`类,然后创建一个`MyClass`对象`my_obj`并调用其中的`print_data`方法,输出了`my_list`中的值。
阅读全文
相关推荐


















