如何从模块导入实例化的对象

时间:2019-04-26 17:14:51

标签: python oop

尝试导入模块及其实例化的对象,但一直说该对象不存在。

car.py

class Car:

    def __init__(self, year, make, model):
        self.year = year
        self.make = make
        self.model = model

    def __str__(self):
        return "Make: {} Model: {} Year: {}".format(self.make, self.model, self.year)

stratus = Car(1995, "Dodge", "Stratus")

main.py

import car

print(stratus.__str__())

应打印汽车的属性,但返回错误: NameError:名称“ stratus”未定义

1 个答案:

答案 0 :(得分:2)

要么:

import car
print(car.stratus)

from car import stratus
print(stratus)