制作我自己的python模块

时间:2016-05-30 00:48:34

标签: python

我已经创建了一个python类,我希望能够通过运行import car来使用它,我相信它是正确的语言。目前,我可以在我的类中使用任何东西的唯一方法是在python3 IDE单击运行中打开文件(/home/pi/Desktop/python/car.py),然后使用我的类。

我相信/usr/lib/python3.4将是适当的地方,但我已经尝试过了,输出就在这里:

>>> import car
>>> my_car = car('n', 'vns', '15', '13')
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    my_car = car('n', 'vns', '15', '13')
TypeError: 'module' object is not callable

类代码可能是不必要的,但在这里:

class car():
        """Your car."""

    def __init__(self, make, model, year, fuel_capacity):
        """Atributtes of your car, fuel in gallons."""
        self.make = make
        self.model = model
        self.year = year
        self.fuel_capacity = fuel_capacity
        self.fuel_level = 0

    def fill_tank(self):
        """Fill up your gas."""
        self.fuel_level = self.fuel_capacity
        print("Fuel tank is full")

    def drive(self):
        """Drive your car"""
        print("The car is moving")
        self.fuel_level = self.fuel_level

    def specs(self):
        print(self.year, self.make, self.model, self.fuel_capacity, "Gallons")

2 个答案:

答案 0 :(得分:2)

首先,不要在Python安装目录中创建本地模块。

由于您未指定PYTHONPATH,因此无法导入模块。 您应该在命令行中导出该模块的路径。 export PYTHONPATH=/home/pi/Desktop/python/

此外,根据PEP8,类名应使用CapWords约定。见https://www.python.org/dev/peps/pep-0008/#id39

现在进入你的python交互式shell,你应该能够导入该模块。

from car import Car

答案 1 :(得分:2)

import car
my_car = car('n', 'vns', '15', '13')
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    my_car = car('n', 'vns', '15', '13')
TypeError: 'module' object is not callable

你在一般的python开发中犯了一些错误,但回答你的问题,为什么它现在不能正常工作:

car.car('n', 'vns', '15', '13')代替car

相关问题