【发布时间】:2018-07-06 01:04:15
【问题描述】:
我在将 Python 作为 OO 语言时遇到了一些问题。我用 Java 和 Python 学习了 OO,虽然相似,但似乎有一些关键的区别。我正在尝试编写一个基本的聊天机器人(我的意思是非常基本的),由于某种原因,我无法从类内部访问变量。这是我的代码:
聊天机器人.py
import random
class Chatbot:
greetings = ["Hello", "WAZZZZZUUUPPPPP", "Howdy"]
salutations = ["Bye", "Bye Felicia", "Adios", "Fine, I didn't want to talk to you anymore anyway"]
how_are_you = ["I'm good", "I've been better", "Better than you"]
whats_up = ["Not much", "Thinking about life, the universe, and everything", "Just wondering why you're communicating with a human in a box"]
def respond(self,text):
myText = text.lower();
print(text)
if text == "hello":
print(self.greetings[random.randint(0, greetings.length - 1)])
这是调用代码,rowdy-messenger.py:
from chatbot import Chatbot
print("Welcome to rowdy messenger")
hello = Chatbot()
hello.respond("hello")
我得到的错误文本是(我省略了绝对路径)
...
File "rowdy-messenger.py", line 5, in <module>
hello.respond("hello")
line 15, in respond
print(greetings[random.randint(0, greetings.length - 1)])
NameError: name 'greetings' is not defined
我的问题:
1) 为什么会出现此错误?我习惯了 Java,这很好(当然使用 this 而不是 self)
2) 将它们用作类变量还是实例变量更好?在调用代码中,无论如何它只会被实例化一次,但我认为对于“大”数据,最好只实例化一次常量。
【问题讨论】:
-
为什么你一次正确地引用了
self.greetings,而第二次却只用了greetings? -
“将它们用作类变量还是实例变量更好?”:由于您不更改它们,因此可以将它们保留为类变量。但是创建实例变量并不会吃掉很多内存;仅供参考。
-
@ŁukaszRogalski 哇,我什至没有意识到这一点,谢谢!
-
@Jean-FrançoisFabre 那么,它不像 Java?它只在内存中创建一个空间,然后设置不同的指针?
-
是的,一模一样
标签: python instance-variables class-variables