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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23238352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:33:55  来源:igfitidea点击:

Create object from class in separate file

pythonclassobjectpackage

提问by Trenera

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):

我已经做了几个关于 Python 的教程,我知道如何定义类,但我不知道如何使用它们。例如,我创建以下文件(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'

Then I create another file (Mercedes.py), where I want to create an object Mercedes from the class Car:

然后我创建另一个文件 (Mercedes.py),我想在其中从 Car 类创建一个对象 Mercedes:

Mercedes = Car('Mercedes', 'S Class', 'Red')

, but I get an error:

,但我收到一个错误:

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)

Which prints:

哪个打印:

Red

So the question is: How can I create an object from a class from different file in the same package (folder)?

所以问题是:如何从同一包(文件夹)中不同文件的类创建对象?

采纳答案by sshashank124

In your Mercedes.py, you should import the car.pyfile as follows (as long as the two files are in the same directory):

在您的 中Mercedes.py,您应该car.py按如下方式导入文件(只要两个文件在同一目录中):

import car

Then you can do:

然后你可以这样做:

Mercedes = car.Car('Mercedes', 'S Class', 'Red')  #note the necessary 'car.'

Alternatively, you could do

或者,你可以做

from car import Car

Mercedes = Car('Mercedes', 'S Class', 'Red')      #no need of 'car.' anymore

回答by Oren T

Simply use the import command in your Mercedes file. There's a good intro about importing in Python in here

只需在您的 Mercedes 文件中使用 import 命令。有关于进口在Python很好的介绍这里