Reputation: 11
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
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
Reputation: 689
So a couple of things have gone wrong with your code:
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')
Upvotes: 1
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