在Python中,子类可以通过以下几种方式调用父类的方法:
1. 直接使用父类的类名来直接调用父类的方法。
class Parent:def __init__(self):print('This is parent init.')def sleep(self):print('Parent sleeps.')class Child(Parent):def __init__(self):Parent.__init__(self) 直接调用父类的构造函数print('This is child init.')def sleep(self):print('Child sleeps.')c = Child()c.sleep() 输出:Parent sleeps. Child sleeps.
2. 使用`super()`函数调用父类的方法。
class Parent:def __init__(self):self.name = 'Parent'def print_name(self):print('Parent Class:', self.name)class Child(Parent):def __init__(self):super().__init__() 调用父类的构造函数self.name = 'Child'def print_name(self):super().print_name() 调用父类的打印方法child = Child()child.print_name() 输出:Parent Class: Parent Child Class: Child
3. 使用`super(type, obj).method(args)`方法调用,其中`type`是子类的类型,`obj`是子类的实例。
class Parent:def __init__(self):self.name = 'Parent'def print_name(self):print('Parent Class:', self.name)class Child(Parent):def __init__(self):super(Child, self).__init__() 使用super()调用父类的构造函数self.name = 'Child'def print_name(self):super().print_name() 使用super()调用父类的打印方法child = Child()child.print_name() 输出:Parent Class: Parent Child Class: Child
4. 使用`super(子类名, self).父类方法名()`方法调用,其中`子类名`是子类的名称,`self`是子类的实例。
class Parent:def __init__(self):self.name = 'Parent'def print_name(self):print('Parent Class:', self.name)class Child(Parent):def __init__(self):super(Child, self).__init__() 使用super()调用父类的构造函数self.name = 'Child'def print_name(self):super(Child, self).print_name() 使用super()调用父类的打印方法child = Child()child.print_name() 输出:Parent Class: Parent Child Class: Child
以上是Python中调用父类方法的几种常见方式。您可以根据需要选择合适的方法
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/81554.html