在单独的文件中从类创建对象

编程入门 行业动态 更新时间:2024-10-10 06:22:15
本文介绍了在单独的文件中从类创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经完成了一些关于Python的教程,并且我知道如何定义类,但是我不知道如何使用它们.例如,我创建以下文件(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

然后您可以执行以下操作:

Then you can do:

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

更多推荐

在单独的文件中从类创建对象

本文发布于:2023-11-26 09:01:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633471.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!