1

I am a C developer and I have decided to pick up python as well. I can't to figure out why I am unable to create an instance of a class I made inside of a separate module. Here is my car.py module that contains my Car object

class Car:
    type = ""
    def __init__(self, type):
        self.type = type

And here is my other module that I am trying to use the Car object in

import car
x = Car()
print(x.type)

I get an error that says "Undefined variable 'Car' pylint(undefined-variable)" on the third line where I instantiate the car variable

I am also having trouble relocation the module to another directory within my project. The directory is named 'objects'. When I try to import the module, it says "No name 'car' in module 'objects' pylint(no-name-in-module)". Here is my import

from objects import car
  • 2
    Other answers have sorted out your import/module scoping related problem. You also need to pass a value for type when creating the object: x = Car(type). – mhawke Feb 20 '21 at 04:52
  • 2
    Also, type is a built in function in Python so you should be careful that your use of it doesn’t shadow the built in. – mhawke Feb 20 '21 at 04:53

3 Answers3

2

Try:

import car

x = car.Car()
print(x.type)

Also, you can use:

from car import Car

x = Car()
print(x.type)
Muhammad Yasirroni
  • 1,512
  • 12
  • 22
1

An import statement creates a reference to the named object in your namespace, loading the module that contains it if necessary. Modules are objects too.

import car

This statement creates a reference to the car module in your global namespace. The module object has a class object named Car as one of its attributes. You can access it with

x = car.Car()

You can import more selectively using the from keyword. That way, instead of creating a name car in your namespace, you can bind the name(s) you want directly:

from car import Car

With this form of the import statement, your code should work directly.

On a related note, you can also use the as keyword to change the name that the imported object gets bound to, as though with an assignment:

from car import Car as Auto

x = Auto()

or

import car as auto

x = auto.Car()
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

When creating a module and importing it you to specify the namespace to create a instance

This can be done in two ways, specifying the namespace while creating the instance or making the namespace available to the whole file:

from car import * or from car import Car if you just want the car class.

then you can do x = Car

Alternatively you can import the module and specify the namespace while creating the instance:

import car
car = car.Car()
  • 1
    Please don't advise the OP to use `from car import *` -- it is not a good idea. [Should wildcard import be avoided?](https://stackoverflow.com/questions/3615125/should-wildcard-import-be-avoided) – costaparas Feb 20 '21 at 06:23