Félix Bernard
Félix Bernard

Reputation: 75

NameError: class name is not defined

I can't find why this piece of code won't work:

class Agent:
def hello(self, first_name):
    return "Bien le bonjour" + first_name + "!"
agent = Agent()
print(agent.hello("Félix"))

I'm pretty sure to run it under python3 since i just follow a tutorial on how to create a local envirement for python3.

It return

    class Agent:
  File "la_poo_avec_python-00_setup/model.py", line 4, in Agent
    agent = Agent()
NameError: name 'Agent' is not defined
(my_env) noob@Flex:~/Noobi/prog/python3env/my_env$ 

Upvotes: 3

Views: 49312

Answers (3)

HosseinOj
HosseinOj

Reputation: 48

The syntax you used sounds correct, but you need to make some corrections:

  • You need to separate your class from the main code as below because interpreter thinks that the line 4 and what is after that belong to your class:
class Agent:
    def hello(self, first_name):
        return "Bien le bonjour" + first_name + "!"

agent = Agent()
print(agent.hello("Felix"))
  • You may have to replace "l'accent aigu" with "e" in "Felix" as it can reflect you an error regarding using "Non-ASCII" character in the code.
  • Indentation is another error that I got from you code. So, please make sure it is organized properly before running.

Upvotes: 0

shamilpython
shamilpython

Reputation: 485

The class needs an __init__ method. As other answers suggest, fix the indention and do this:

class Agent:
    def __init__(self):
        pass

    def hello(self, first_name):
        return "Bien le bonjour" + first_name + "!"

Upvotes: -2

PMonti
PMonti

Reputation: 460

Your code is correct, but I suspect there is something wrong with the indentation. This is how it should be

class Agent:
    def hello(self, first_name):
        return "Bien le bonjour" + first_name + "!"
agent = Agent()
print(agent.hello("Félix"))

Upvotes: 6

Related Questions