无法使用python继承调用函数吗?

问题描述 投票:1回答:1

我是python的新手,请帮助我解决以下问题-

问题:您已经给了一个类base,现在您必须声明一个名为code的类,该类继承了类base并调用了hello类的base

示例:

  • 输入:4
  • 输出:["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)]

我尝试如下:

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

但出现错误:

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
python inheritance
1个回答
0
投票

关于错误:

base.hellounbound方法。

x.hello()转换为code.hello(x),并且range函数接受int类型的变量。这清楚地说明了为什么要给出TypeError: 'code' object cannot be interpreted as an integer。现在寻求解决方案

有两种方法可以使这项工作

1)因此,在不更改base类的情况下使其起作用:

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

2)或更改方法类型(绑定方法):

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

为了更清楚地了解绑定的,未绑定的静态方法Bound, unbound and static method

有关class, static, instance方法的更多信息,请参考Python method types in classes

© www.soinside.com 2019 - 2024. All rights reserved.