【问题标题】:Accessing instance variables inside a class in Python 3 [closed]在 Python 3 中访问类中的实例变量 [关闭]
【发布时间】: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


【解决方案1】:

问题在于您没有始终如一地使用self。该行指的是greetings 两次;第一次使用self,但第二次不使用。

Python 的“显式胜于隐式”理念意味着您始终需要使用self

但请注意,代码可以简化为 print(random.choice(self.greetings))

【讨论】:

  • 我什至没有注意到第二个“问候”缺少自我,谢谢!另外,我不知道选择方法,我想我需要更彻底地阅读文档>.
【解决方案2】:

https://syntaxdb.com/ref/python/class-variables

如果您打算将问候语作为实例变量(看起来确实如此),您还需要在问候语声明前加上 self 前缀。

这是 python 对 OOP 的理解与 Java 的众多差异之一(问候声明中不需要 this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-11
    • 2019-02-27
    • 2020-04-05
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多