954,546 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Python problem

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

Laurence26
Newbie Poster
5 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

There is no way to tell since the code you use to import is not included. Here is a link to the "Dive Into Python" chapter on import http://diveintopython.org/object_oriented_framework/importing_modules.html

woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

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

class Tank():


Somewhere, for your code to work.

linux
Posting Shark
933 posts since Aug 2006
Reputation Points: 118
Solved Threads: 30
 

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"

sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212
 

Well,
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.

Laurence26
Newbie Poster
5 posts since Mar 2008
Reputation Points: 10
Solved Threads: 0
 

You did not fix the misnamed __init__() function in your class!
These are double underlines front and back!

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

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

umbuty
Newbie Poster
1 post since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You