Question

I have a class A and I have inherited a class B from class A. I have two methods methodX & methodY in ClassA. This methodY will be calling methodX in classA. Now I have a methodZ in ClassB.

The following is the scenario:-

class A(object):
 def methodX(self):
  ....
 def methodY(self):
  methodX()

class B(A)
 def methodZ(self):
  self.methodY() #says the global methodX is not defined 

My question is that I have to call methodY which inturn calls methodX from methodZ. How is it possible? Should I define the methodX globally ? Or is there any other alternative.. Thanks in advance !

Était-ce utile?

La solution 2

As it has been said before, using self.methodX() seems to be solving your problem. Check this:

class A(object):
    def methodX(self):
        print "A.methodX"
    def methodY(self):
        print "A.methodY"
        self.methodX()

class B(A):
    def methodZ(self):
        print "B.methodZ"
        self.methodY()

b = B()
b.methodZ()

Generates this output:

$ python test.py
B.methodZ
A.methodY
A.methodX
$

Which I think it's what you were looking for...

Autres conseils

In methodY you should be calling self.methodX().

Since a member function cannot be called without using the object of that class, this error is thrown. Using

self.methodX()

Calls the function methodX() using the object using the object used to call the methodY()

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top