我是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
关于错误:
base.hello
是unbound方法。
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