继承:如何调用父类的方法?

2024-06-09 03:07:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我上了以下三节课IndiaStates的父类,StatesDistrict的父类。我定义了一个District类的对象。当我尝试运行India类的方法时,它给出了一个错误。请帮助我如何运行它

class India:
    def __init__(self):
        print("Country is India")
    def functionofindia(number):
        rvalue=number*2
        return rvalue   

    
class States(India):
    def __init__(self,nameofstate):
        super().__init__()
        print("state is {}".format(nameofstate))


class District(States):
    def __init__(self,nameofstate, nameofdistrict):
        super().__init__(nameofstate)
        print("District is {}".format(nameofdistrict))


HP=District("Himachal Pradesh","Mandi")
print(HP.functionofindia(2))

错误是:

Country is India
state is Himachal Pradesh
District is Mandi
Traceback (most recent call last):
  File "c:\Users\DELL\OneDrive\Desktop\practice\oops.py", line 23, in <module>
    print(HP.functionofindia(2))
TypeError: functionofindia() takes 1 positional argument but 2 were given

Tags: selfinitisdef错误countryclasshp
1条回答
网友
1楼 · 发布于 2024-06-09 03:07:24

要使用这样的类方法,应该将self作为方法定义中的第一个参数传递。所以你们班的印度变成了:

class India:
    def __init__(self):
        print("Country is India")
    def functionofindia(self, number):
        rvalue=number*2
        return rvalue

当方法与类的任何属性都不相关时,也可以用静态方法替换它。请参阅有关静态方法here的详细信息。采用静态方法的印度:

class India:
    def __init__(self):
        print("Country is India")

    @staticmethod
    def functionofindia(number):
        rvalue=number*2
        return rvalue

相关问题 更多 >