python的super方法_python-super().method()和self.method()有什么区别

博客介绍了Python中self和super()的概念。self是类实例方法的首个参数,代表类的调用对象。super()用于引用父类对象,在方法重写时很有用,还给出了Java中super()调用父类构造函数的情况,并通过代码示例展示了二者的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

self

self,通常用作类的实例方法的第一个参数,它始终表示类的调用对象/实例.

super()

super()引用父类的对象.它在方法重写的情况下很有用,在包括C,Java等多种编程语言的情况下也是有用的.在Java中,super()用于调用父类的构造函数.

请看下面的小例子.

class TopClass(object):

def __init__(self, name, age):

self.name = name;

self.age = age;

def print_details(self):

print("Details:-")

print("Name: ", self.name)

print("Age: ", self.age)

self.method()

def method(self):

print("Inside method of TopClass")

class BottomClass(TopClass):

def method(self):

print("Inside method of BottomClass")

def self_caller(self):

self.method()

def super_caller(self):

parent = super()

print(parent)

parent.method()

child = BottomClass ("Ryan Holding", 26)

child.print_details()

"""

Details:-

Name: Ryan Holding

Age: 26

Inside method of BottomClass

"""

parent = TopClass("Rishikesh Agrawani", 26)

parent.print_details()

"""

Details:-

Name: Rishikesh Agrawani

Age: 26

Inside method of TopClass

"""

child.self_caller()

child.super_caller()

"""

Inside method of BottomClass

, >

Inside method of TopClass

"""

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值