Not Defined error in basic code

Jason Friedman jsf80238 at gmail.com
Thu Mar 14 10:21:08 EDT 2019


On Thu, Mar 14, 2019 at 8:07 AM Jack Dangler <tdldev at gmail.com> wrote:

> <file: class_weapon.py>
>
> class weapon:
>      weaponId
>      manufacturerName
>
>      def printWeaponInfo(self):
>          infoString = "ID: %d Mfg: %s Model: %s" % (self.weaponId,
> self.manufacturerName)
>          return infoString
>
> <file: weaponTrack.py>
>
> import class_weapon
>
> MyWeapon=weapon()
> MyWeapon.weaponId = 100
> MyWeapon.manufacturerName = "Glock"
>
> print(MyWeapon.printWeaponInfo)
>
> executing 'python3 weaponTrack.py' results in this bailing on the first
> element in the class with "not defined".


Try running your module file by itself, that will give you a clue:

$ python3 class_weapon.py
Traceback (most recent call last):
  File "class_weapon.py", line 1, in <module>
    class weapon:
  File "class_weapon.py", line 2, in weapon
    weaponId
NameError: name 'weaponId' is not defined

You have another error in the file which will be revealed when you get it
to compile.

Also, your printWeapon method could renamed to __repr__ or __str__ (see
https://docs.python.org/3/reference/datamodel.html#object.__repr__)

Also most Python programmers would spell MyWeapon as my_weapon (see
https://www.python.org/dev/peps/pep-0008/).



More information about the Python-list mailing list