-1

I am new to object oriented world and trying following code in python and calling function of one class from another class.

Mycode.py

class A:

def funcA():
    return "sometext"

def funcB(self):
    self.funcA()  # calls func A internally from funcB 

secondcode.py

from Mycode import A

class B:
      def funcC(self):
          A.funcB(self)  # it gives error for call funcA() as it is unknown to class B
if __name__ == '__main__':

b=B()
b.funcC()

AttributeError: 'B' object has no attribute 'funcA' How does scoping work with respect to classes in python?

Manish
  • 3,341
  • 15
  • 52
  • 87
  • Could you fix the indentation here so that it's identical to the files on your computer? – Patrick Haugh Oct 23 '18 at 14:35
  • 1
    Hi, welcome to Python. Indention is very important in Python. Please make sure your indention is correct before submitting your question. – Sraw Oct 23 '18 at 14:35
  • Also I believe there is an error in `def func C(self): ` line. Please fix it so that your code is syntatically correct and well indented. – running.t Oct 23 '18 at 14:37

1 Answers1

0

The problem is not scope, but you have misunderstanding on self.

class B:
      def func C(self):
          A.funcB(self) 

In the above code, self is an instance of B instead of A. But A.funcB should accept an instance of A. Or self.funcA in A.funcB is unavaliable.

Sraw
  • 18,892
  • 11
  • 54
  • 87
  • I think the problem is about understanding of [bound and unbound functions in python](https://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static) – running.t Oct 23 '18 at 14:40
  • I am new can someone fix the issue here so that i can call funcB from using A.funcB which should call internally funcA internally? – Manish Oct 23 '18 at 14:42
  • @running.t I somehow disagree. Because many new comers think that `self` is a key word or let's say magic word like `this` in Java. But actually it isn't. It is just a normal variable. It can be whatever you want. It can be `def funcC(hahah):`. And if you use `hahah` as `self`, it can still work. – Sraw Oct 23 '18 at 14:42
  • Still i could not understand. Pls help me in fixing my code. – Manish Oct 23 '18 at 14:48
  • @Manish It's hard to fix in this structure. Basically you need at least an instance of `A`. like `a = A() a.funcB()`. – Sraw Oct 23 '18 at 14:51