0

Team: I am new to python and doing my first implementation of class. probably am missing some learning from online tutorials. please help clarify why am I not able to print the variable that is attribute of a function def of a class. I want expected output. not sure what concept am missing. Please clarify. thanks. I don't know how to use return in my use case. Please clarify with working code.

code

class testClass:
    def __init__(self):
        classVar = "classString"

    def Func1(self):
        self.testVar1 = "string1"
        print("in f1")


    def Func2(self):
        self.testVar2 = "string2"
        print("in f2")

tco = testClass()

tco.Func1()
tco.Func2()

tcfo=tco.Func1()
print(tcfo.testVar1)

output

class-example.py
in f1
in f2
in f1
Traceback (most recent call last):
  File "/python/class-example.py", line 20, in <module>
    print(tcfo.testVar1)
AttributeError: 'NoneType' object has no attribute 'testVar1'

expected output

in f1
in f2
in f1
string1
AhmFM
  • 1,552
  • 3
  • 23
  • 53
  • Your clue is in the error: `AttributeError: 'NoneType' object` - your `testClass.Func1` function doesn't return a value – Nick Sep 08 '22 at 04:43
  • But you should probably `print(tco.testVar1)` – Nick Sep 08 '22 at 04:44
  • i get the clue but am still not able to implement it. I used `return` and i get same output no change. – AhmFM Sep 08 '22 at 04:52
  • `tco.Func1()` doesn’t return anything, so `tcfo` is `None`. Not sure what else you expected it to be… – deceze Sep 08 '22 at 04:53
  • i think am not at your level yet to understand your comment. sorry for my dumbness. please specify code to fix and then I can walk over it myself and comprehend. – AhmFM Sep 08 '22 at 04:55
  • Why do you expect `tcfo.testVar1` to work at all? What do you think it does and why? It’s unclear whether we should help you fix the code so this piece works, or whether you’re simply confused about that piece and should maybe remove it. – deceze Sep 08 '22 at 04:57
  • `tcfo=tco.Func1()` i used this thinking this way it creates an object of the function then I can print using that object `tcfo` the variable it contains. – AhmFM Sep 08 '22 at 04:58
  • It does not. It assigns whatever `Func1` `return`s to `tcfo`. This isn’t any different than normal functions. – deceze Sep 08 '22 at 05:01
  • added return like `return self.testVar1` in def `Func1` and get `AttributeError: 'str' object has no attribute 'testVar1'` – AhmFM Sep 08 '22 at 05:04
  • i figured out. I had to do `return self` in each function definition and i just had to guess it to understand. but process of returning was new to me which helped through your link but what to return was not clear and that i had to guess. thanks – AhmFM Sep 08 '22 at 05:07

0 Answers0