我不明白为什么这段代码不能工作:
class Agent:
def hello(self, first_name):
return "Bien le bonjour" + first_name + "!"
agent = Agent()
print(agent.hello("Félix"))我非常确定我会在python3下运行它,因为我只需要遵循一个教程:https://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-local-programming-environment-on-ubuntu-16-04关于如何为python3创建一个本地环境。
它返回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$
发布于 2017-05-01 15:58:22
您的代码是正确的,但我怀疑缩进有问题。事情应该是这样的。
class Agent:
def hello(self, first_name):
return "Bien le bonjour" + first_name + "!"
agent = Agent()
print(agent.hello("Félix"))发布于 2018-12-25 18:54:42
该类需要一个__init__方法。正如其他答案所建议的,修复缩进并执行以下操作:
class Agent:
def __init__(self):
pass
def hello(self, first_name):
return "Bien le bonjour" + first_name + "!"发布于 2019-07-10 20:49:58
您使用的语法听起来是正确的,但您需要进行一些更正:
如下所示,您需要将您的类与主代码分开,因为
class Agent:
def hello(self, first_name):
return "Bien le bonjour" + first_name + "!"
agent = Agent()
print(agent.hello("Felix"))你可能不得不在"Felix“中用"e”替换“l‘’accent aigu”,因为它可以反映出一个关于在code.
https://stackoverflow.com/questions/43715953
复制相似问题