首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

为什么在使用super()时我必须指定自己的类,有没有办法解决它?

在Python中,super()函数用于调用父类的方法。当你在子类中使用super()时,必须指定当前类,以便在调用父类方法时正确地传递参数。

例如,如果你有一个名为MyClass的子类,它继承自ParentClass,你需要在MyClass中使用super()来调用ParentClass的方法。这是一个示例:

代码语言:python
代码运行次数:0
复制
class ParentClass:
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

class MyClass(ParentClass):
    def __init__(self, arg1, arg2, arg3):
        super(MyClass, self).__init__(arg1, arg2)
        self.arg3 = arg3

在这个例子中,MyClass继承自ParentClass,并在__init__方法中使用super()来调用ParentClass__init__方法。

如果你不指定当前类,super()将无法正确地传递参数,从而导致错误。因此,在使用super()时,必须指定当前类。

如果你希望避免在使用super()时指定当前类,可以考虑使用__class__属性。例如:

代码语言:python
代码运行次数:0
复制
class MyClass(ParentClass):
    def __init__(self, arg1, arg2, arg3):
        super(__class__, self).__init__(arg1, arg2)
        self.arg3 = arg3

在这个例子中,__class__属性将自动传递当前类,因此你不需要显式地指定当前类。

总之,在使用super()时必须指定当前类,以便正确地传递参数。如果你希望避免这种情况,可以考虑使用__class__属性。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券