Create object from class in separate file(从单独文件中的类创建对象)
问题描述
我已经完成了几个关于 Python 的教程,并且我知道如何定义类,但我不知道如何使用它们.例如,我创建了以下 file (car.py):
I have done several tutorials on Python and I know how to define classes, but I don't know how to use them. For example I create the following file (car.py):
class Car(object):
condition = 'New'
def __init__(self,brand,model,color):
self.brand = brand
self.model = model
self.color = color
def drive(self):
self.condition = 'Used'
然后我创建另一个文件 (Mercedes.py),我想从 Car 类中创建一个对象 Mercedes:
Then I create another file (Mercedes.py), where I want to create an object Mercedes from the class Car:
Mercedes = Car('Mercedes', 'S Class', 'Red')
,但我得到一个错误:
NameError: name 'Car' is not defined
如果我在创建实例(汽车)的同一个文件中创建实例(对象),我没有问题:
If I create an instance (object) in the same file where I created it (car), I have no problems:
class Car(object):
condition = 'New'
def __init__(self,brand,model,color):
self.brand = brand
self.model = model
self.color = color
def drive(self):
self.condition = 'Used'
Mercedes = Car('Mercedes', 'S Class', 'Red')
print (Mercedes.color)
哪些打印:
Red
所以问题是:如何从同一个包(文件夹)中不同文件的类创建对象?
So the question is: How can I create an object from a class from different file in the same package (folder)?
推荐答案
在你的 Mercedes.py 中,你应该按如下方式导入 car.py 文件(只要因为这两个文件在同一个目录):
In your Mercedes.py, you should import the car.py file as follows (as long as the two files are in the same directory):
import car
那么你可以这样做:
Mercedes = car.Car('Mercedes', 'S Class', 'Red') #note the necessary 'car.'
或者,你可以这样做
from car import Car
Mercedes = Car('Mercedes', 'S Class', 'Red') #no need of 'car.' anymore
这篇关于从单独文件中的类创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从单独文件中的类创建对象
基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
