Not able to call a function using the python inheritance?

I am new to python, please help me with the below question-

Question: You have already given a class base, now you have to declare a class called code which inherits the class base and calls the hello of the base class.

Example:

  • Input: 4
  • Output: ["Hello Python", "Hello Python", "Hello Python", "Hello Python"]
class base:
    def __init__(self,n):
        self.n=n
    def hello(n):
        return ["Hello Python" for i in range(n)]

I tried as below:

class code(base):
    def __init__(self):
        base.__init__(self,5)
x=code()
x.hello()

but got error:

TypeError                                 Traceback (most recent call last)
<ipython-input-88-1a7429b02c84> in <module>
     12         base.__init__(self,5)
     13 x=code()
---> 14 x.hello()

<ipython-input-88-1a7429b02c84> in hello(n)
      3      self.n=n
      4     def hello(n):
----> 5         return ["Hello Python" for i in range(n)]
      6 
      7 

TypeError: 'code' object cannot be interpreted as an integer

1 answer

  • answered 2019-12-16 03:01 root163

    About the error:

    base.hello is unbound method.

    x.hello() is translated to code.hello(x) and range function takes in int type variables. This makes it clear why it is giving TypeError: 'code' object cannot be interpreted as an integer. Now for solution

    There are two ways to make this work

    1)So to make this work without changing base class:

    class code(base):
        def __init__(self):
            base.__init__(self,5)
    x = code()
    code.hello(x.n)
    

    2) Or change the method type(bound method):

    class base:
        def __init__(self,n):
            self.n=n
        def hello(self):
            return ["Hello Python" for i in range(self.n)]
    

    For more clarity on bound, unbound, static methods Bound, unbound and static method

    For more on class, static, instance methods, refer to Python method types in classes