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

Inheritance: how to call method of parent class?

我做了以下 3 classes。 IndiaStates 的父级 class,StatesDistrict 的父级 class。我定义了 District class 的 1 个对象。当我尝试 India class 的 运行 方法时,它给出了一个错误。请帮助我如何运行它。

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

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

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

当该方法与class的任何属性无关时,您也可以将其替换为静态方法。查看有关静态方法的更多信息 here。印度用静态方法:

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

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