1

I have written a class called cl:

class cl :
def __int__(self):
    self.a = 0


def increment(self):
    self.a +=1

def print_a(self):
    print ("value : "+str(self.a))

I have written another class called test. However, I got an error when calling methods.

 from cl import *

class test :
    def __int__(self):
        self.b = 0
        self.c = cl()


def main(self):
    self.c.increment()
    self.c.print_a()
    self.c.increment()
    self.c.print_a()

d = test()
d.main()

What I got is this:

 Traceback (most recent call last):
  File "test_file.py", line 19, in <module>

    d.main()
  File "test_file.py", line 12, in main
    self.c.increment()
AttributeError: test instance has no attribute 'c'

Can anyone explain why that happens and what is the issue with my code? I am a high school student. Can you explain to me? And can you help me to fix this?

etution lanka
  • 83
  • 1
  • 11

2 Answers2

3

You're misspelling __init__ with __int__:

class cl :
    def __int__(self):
        self.a = 0

Should be

class cl :
    def __init__(self):
        self.a = 0

Note that encompassing a main method inside of the test class is really an anti-pattern in Python; the form of

def main():
    ...

if __name__ == "__main__":
    main()

is preferred and is more Pythonic.

For some reference on the if __name__ == "__main__" pattern, see:

Community
  • 1
  • 1
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
1

main function does not belong the class test , it belongs the test.py which your test class in, so the self in main is test.py , not test

freeeze king
  • 489
  • 2
  • 6
  • 13