Kam Kam - 1 month ago 8
Python Question

using inheritance and calling in other class

code:

class aa:
def getDis():
return 0

class bb(aa):
def getDis():
return 10

class cc(aa):
def getDis():
return 15

class d:
def __init__(self,cust):
self.cust = cust
self.memberLevel = aa()

def cgl(self,amt):
if amt ==1:
self.memberLevel = bb()
elif amt ==2:
self.memberLevel = cc()
else:
self.memberLevel = aa()


Well i have these four classes. What i am trying to do is that in my top three classes i have inheritance. In my class d i am trying to call the respective method if the amount is 1 0r 2 . Instead it is giving me this output:

d1 = d('one')
d1.cgl(1)
print(d1.memberLevel)


output:

<__main__.bb object at 0x036D7BF0>


So help required that how can i use overriding technique.

Answer

It seems you were hoping to see the console output:10

Because d1.memberLevel is the bb class itself (not the value 10, and not the function that returns the value 10), the console output shows <__main__.bb object at 0x036D7BF0>. This is correct behavior when printing an object directly.

Perhaps your last line of console code should say:

print(d1.memberLevel.getDis())

Another option would be to assign the value within the "d" class:

self.memberLevel = bb().getDis()

And the member methods require "self", e.g.:

def getDis(self):
    return 10
Comments