Arun Prakash
Arun Prakash

Reputation: 11

I'm getting Name error for my python class attributes

I've just started learning Python and I was trying out class concept and came across this error and cant find out what I've done wrong ! Can someone point out ?!

class animal:
    def __init__(self,name,ani,age,location):
        self.name= name
        self.ani = ani
        self.age = age
        self.location = location

    def info(self):
        print("I'm a {0} called {1} and I'm {2} years old, living in {3}".format(ani,name,age,location))


Arun = animal(Martin,Dog,7,Amazon)
Arun.info()

And the error is :

Traceback (most recent call last):   File
"C:\Users\DELL\Desktop\python\class_trail.py", line 12, in <module>
Arun = animal(Martin,Dog,7,Amazon) NameError: name 'Martin' is not defined

Upvotes: 1

Views: 191

Answers (3)

Rocco Fortuna
Rocco Fortuna

Reputation: 291

The error you are getting refers to the fact that no variable Martin is defined in the code, before you use it. What you probably meant to do is

Arun = animal("Martin", "Dog", 7, "Amazon")

Note the quotes around the strings you are passing as parameters, as opposed to how python interprets your code, where this would work:

name = "Martin"
animal = "Dog"
age = 7
location = "Amazon"

Arun = animal(name, animal, age, location)

Extra: something you may want to get used to while learning to code in Python are its good practices. Python classes are typically declared with a capital letter (or actually PascalCase), like so class Animal():, while variable names are typically declared lower case (snake_case), like so arun = Animal(...).

There is a small exception: constants are declared all capital, like so EULER_CONSTANT = 0.577.

Upvotes: 0

jrmylow
jrmylow

Reputation: 689

So a couple of things have gone wrong with your code:

  1. You are passing in variable names, not strings.

When you call Arun = animal(Martin,Dog,7,Amazon), Python looks for a variable name called Martin, but doesn't find one and raises NameError.

What you probably intended was Arun = animal('Martin','Dog',7,'Amazon')

  1. Your .info() method needs to refer to self.ani and self.age etc., because those data items are bound up inside the object.

Upvotes: 1

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

Arun = animal(Martin,Dog,7,Amazon)

^ you want to pass here string values, but instead you're passing there variables which are not defined. To pass there strings you have to wrap them into quotes like this:

Arun = animal("Martin","Dog",7,"Amazon")

Upvotes: 0

Related Questions