I found this little program for a game in a book.

class Tank (object):
	def _init_(self, name):
		self.name = name
		self.alive = True
		self.ammo = 5
		self.armor = 60

It is named tank.py
When I import it in python and I try to add

my_tank = Tank("Bob")

Python gives an error
NameError: name 'Tank' is not defined

Does anyone has an idea to solve this problem

10 Years
Discussion Span
Last Post by umbuty

Tank() is a class defined by your application. So you would have to have:

class Tank():

Somewhere, for your code to work.


You major problem is that __init__() uses double underlines prefix and postfix.

Also, remember that the module name and its file name are case sensitive!

Here is an example:

# save module as tank.py  (file name is case sensitive!)

class Tank (object):
    def __init__(self, name):
        self.name = name
        self.alive = True
        self.ammo = 5
        self.armor = 60

# test the module
if __name__ == '__main__':
    mytank = Tank("Bob")
    print mytank.name, mytank.armor  # Bob 60

Your program should import the modules like this:

# module was saved as tank.py (case sensitive)

import tank

mytank = tank.Tank("Bob")

print mytank.name  # Bob

Please make your thread title more specific, instead of "Python Problem" use "Problem with Python Class"


Thanks for the ideas but none if them have worked.
I now get an error
TypeError: default _new_ takes no parameters.
I have really no idea to solve this problem.


Yea buddie maybe your error is the double underlines, they look like one big underline but are indeed two underlines together __ = _+_

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.