python中的super

Python中的super()函数用于调用父类(超类)的方法。

在Python中,super()是一个内置函数,它用于调用父类(超类)的方法,这个函数的主要作用是在子类中实现多重继承时,可以方便地调用父类的方法,避免了硬编码父类名称的繁琐。

1. super的基本用法

python中的super

super()函数的基本用法如下:

class Parent:
    def __init__(self):
        print("Parent init")
class Child(Parent):
    def __init__(self):
        super().__init__()
        print("Child init")
c = Child()

在这个例子中,Child类继承了Parent类,在Child类的__init__方法中,我们使用super().__init__()来调用父类的__init__方法,当我们创建一个Child类的实例时,会先执行父类的__init__方法,然后执行子类的__init__方法,输出结果如下:

Parent init
Child init

2. super的参数

super()函数可以接受两个参数:第一个参数是当前类,第二个参数是当前类的实例,这两个参数都是可选的,如果不提供,那么默认会调用当前类的父类。

python中的super

class Grandparent:
    def __init__(self, name):
        self.name = name
        print(f"Grandparent {name} created")
class Parent(Grandparent):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age
        print(f"Parent {name} created with age {age}")
class Child(Parent):
    def __init__(self, name, age, gender):
        super().__init__(name, age)
        self.gender = gender
        print(f"Child {name} created with age {age} and gender {gender}")
c = Child("Tom", 10, "male")

在这个例子中,我们在Child类的__init__方法中使用了两个参数的super()函数,首先调用了父类Parent__init__方法,然后再调用祖父类Grandparent__init__方法,输出结果如下:

Grandparent Tom created
Parent Tom created with age 10
Child Tom created with age 10 and gender male

3. super与多重继承

当一个类继承了多个父类时,可以使用super()函数来调用这些父类的方法。

class A:
    def method(self):
        print("A's method")
class B:
    def method(self):
        print("B's method")
        super().method()   调用A的method方法
class C(A, B):   C继承了A和B两个父类
    pass
c = C()
c.method()   输出:B's method -> A's method -> None

在这个例子中,类C继承了类A和类B,在类B的method方法中,我们使用super().method()来调用类A的method方法,当我们创建一个C类的实例并调用其method方法时,会先执行类B的method方法,然后依次执行类A和类B的method方法,输出结果如下:

python中的super

B's method -> A's method -> None

4. super与静态方法和属性

虽然Python中的静态方法和属性不能直接通过实例访问,但我们仍然可以使用super()函数来调用父类的静态方法和属性。

class A:
    @staticmethod
    def static_method():
        print("A's static method")
        print("A's static attribute:", A.static_attribute)   访问静态属性需要通过类名访问,而不是实例名访问
        A.static_attribute = "new value"   修改静态属性需要通过类名访问和修改,而不是实例名访问和修改
        print("A's static attribute:", A.static_attribute)   输出:new value -> None -> new value -> None -> new value -> None ...(每次调用都会更新静态属性的值)

在这个例子中,我们定义了一个静态方法和一个静态属性,在静态方法中,我们使用super()函数来调用父类的静态方法和属性,当我们创建一个A类的实例并调用其静态方法时,会先执行父类的静态方法,然后执行子类的静态方法,输出结果如下:

原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/264917.html

(0)
K-seoK-seoSEO优化员
上一篇 2024年1月27日 02:54
下一篇 2024年1月27日 02:56

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

免备案 高防CDN 无视CC/DDOS攻击 限时秒杀,10元即可体验  (专业解决各类攻击)>>点击进入