Attribute Error when using self

1.4k Views Asked by At

I have this small script implementing a single class with two functions. I wanted to simply print a value that was found in the first function from the second function when I call it from outside of the class.

Problem
It seemed really simple after reading this article over self, but nothing I try seems to be working. I keep getting attribute errors:

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)

Returns...

AttributeError: 'search' object has no attribute 'here'

Question
How can I modify this script to achieve the result I am looking for?

2

There are 2 best solutions below

4
On BEST ANSWER

define 'here'

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

   def test(self):
     ...
0
On

the problem is you never execute the function test(self) which initiate the variable. you can call it using s.test() before s.tester()