Recently I started learning python and ran into a problem. For example:

class B: def __init__(self): self.count= 1 def setCount(self,count): self.count+=count class A: def __init__(self): self.b = B def inc(self): self.b.setCount(20) if __name__ == "__main__": a = A a.inc() 

Throws an error TypeError: inc () missing 1 required positional argument: 'self' How to pass the self object b of class B when calling a.inc ().

  • The constructor must be called a = A() - Sergey Gornostaev

1 answer 1

 class B: def __init__(self): self.count = 1 def setCount(self, count): self.count += count class A: def __init__(self, obj): self.b = obj def inc(self): self.b.setCount(20) if __name__ == "__main__": b = B() a = A(b) a.inc() print(b.count)