【问题标题】:Attribute Error when using self使用 self 时出现属性错误
【发布时间】:2017-01-06 03:36:58
【问题描述】:

我有这个小脚本实现一个具有两个函数的类。当我从类外部调用第二个函数时,我想简单地打印在第一个函数中找到的值。

问题
在通过自我阅读此article 后似乎真的很简单,但我尝试的任何方法似乎都没有奏效。我不断收到属性错误:

class search:
   def test(self):
      self.here = 'hi'
      self.gone = 'bye'
      self.num = 12

   def tester(self):
      return "{}".format(self.here)

s = search()
s.tester()
print (s.gone)

返回...

AttributeError: 'search' 对象没有属性 'here'

问题
如何修改此脚本以达到我想要的结果?

【问题讨论】:

    标签: python-3.x self


    【解决方案1】:

    定义“这里”

    class search:
       here=None
       def __init__(self):
         self.here='hi'
    
       def test(self):
         ...
    

    【讨论】:

    • 我想保留在第一个函数中分配的值。这只会使该全局变量为 null 并且不打印任何内容。
    • 然后使用构造函数__init __设置值,更新
    • 啊,这就是我要找的。抱歉,python 新手。
    • 太棒了!欢迎来到 python,玩得开心。
    【解决方案2】:

    问题是您从不执行启动变量的函数 test(self)。您可以在 s.tester() 之前使用 s.test() 调用它

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2021-07-01
      • 2021-08-07
      相关资源
      最近更新 更多