python super()函数 私有属性 多态 类属性和实例属性

Python类继承及super()函数 文章目录Python中单类继承普通类方法继承初始化函数继承Python中多类继承 Python中单类继承 Python是一门面向对象的编程语言,支持类继承。新的类称为子类(Subclass),被继承的类称为父类、基类或者超类。子类继承父类后,就拥有父类的所有特性。类继承的简单例子: 普通类方法继承 class Fruit(): def color(self): print(... 阅读详情
#5. super()函数
# super() 函数是用于调用父类(超类)的一个方法。
# super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,
# 但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
# MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
# 语法 : super(type[, object-or-type])
# type -- 类
# object-or-type -- 类,一般是 self
# Python 3可以直接使用super().xxx代替 super(Class, self).xxx
#5.1
class Animal():
    def __init__(self):
        self.hungry = True
        print('Animal class')
    def eat(self):
        if self.hungry:
            print('Need eat')
        else:
            print('Do not need eat')

# class Dog(Animal):
#     def __init__(self):
#         self.walk = "run"
#         print('Dog class')
#     def walkway(self):
#         print(self.walk)

# dog = Dog()
# dog.walkway()
# dog.eat() #报错 AttributeError: 'Dog' object has no attribute 'hungry'
#这里子类没有继承父类的实例属性

#为了解决这个问题,现在我们重新写过子类
class Dog(Animal):
    def __init__(self):
        #方式一,旧版python使用这种方式
        #Animal.__init__(self)
        #方式二,新版python使用这种方式
        super().__init__()
        self.walk = "run"
        print('Dog class')
    def walkway(self):
        print(self.walk)

# dog = Dog()
# dog.walkway()
# dog.eat() #输出 Need eat

#5.2菱形继承
#B,C继承 A, D 继承 B,C
#使用super()可以很好的避免构造函数被调用两次
class A():
    def __init__(self):
        print('enter A')
        print('leave A')

class B(A):
    def __init__(self):
        print('enter B')
        super().__init__()
        print('leave B')

class C(A):
    def __init__(self):
        print('enter C')
        super().__init__()
        print('leave C')

class D(B,C):
    def __init__(self):
        print('enter D')
        super().__init__()
        print('leave D')

d = D()


#6.定义私有属性
#可以为实例属性和方法设置私有属性,即不能继承
#设置私有属性的方法 : 在属性名和方法名前面加上两个下划线 __

class Father():
    def __init__(self):
        self.__money = 100
        self.hair = '卷发'
    def __print_private_info(self):
        print('This is private method')
    #获取私有属性
    def get_money(self):
        print(f'money = {self.__money}')
    #修改私有属性
    def set_money(self, money):
        self.__money = money


class Son(Father):
    def __init__(self):
        super().__init__()

father = Father()
print(father.hair)
son = Son()
print(son.hair)
#print(son.__money) #报错 AttributeError: 'Son' object has no attribute '__money'

#6.2 获取和修改私有属性值
#私有属性和方法只能在类里面修改和访问
#一般定义函数名 get_xx用来获取私有属性,定义set_xx来修改私有属性
son.get_money()    #输出 money = 100
son.set_money(200)
son.get_money()    #输出 money = 200
#7.多态
#多态是一种使用对象的方式,子类重写父类方法,调用不同子类对象的相同父类方法,可以产生不同的执行结果
#传入不同的对象,产生不同的结果

class Dog():
    def walk(self):   #父类提供统一的方法,空方法也可以
        print('Run')

class ArmyDog(Dog):
    def walk(self):
        print("追击敌人")

class DrugDog(Dog):
    def walk(self):
        print("追查毒品")

class PoliceMan():
    def work_with_dog(self, dog):  #dog参数,即传入的对象,传入不同对象,调用不同方法
        dog.walk()

dog1 = ArmyDog()
dog2 = DrugDog()
police = PoliceMan()
police.work_with_dog(dog1) #输出 追击敌人
police.work_with_dog(dog2) #输出 追查毒品
#8.类属性和实例属性
#8.1 类属性
#类属性就是 类对象 所拥有的属性,它被该类的所有实例对象所共有,注意,共有
#类属性可以使用类对象或者实例对象访问
class Dog():
    tooth = 10  #类属性

wangcai = Dog()
xiaohei = Dog()
print(Dog.tooth)      #输出 10
print(wangcai.tooth)  #输出 10
print(xiaohei.tooth)  #输出 10
wangcai.tooth = 20    #这里通过实例去修改类属性
print(Dog.tooth)      #输出 10
print(wangcai.tooth)  #输出 20
print(xiaohei.tooth)  #输出 10
#我们实验发现,通过实例修改类属性,并不能修改类属性的值
#实际上,通过实体修改类属性,不是在修改类属性,而是创建了一个实例属性
#类属性只能通过类对象修改
Dog.tooth = 30
print(Dog.tooth)      #输出 30
print(wangcai.tooth)  #输出 20
print(xiaohei.tooth)  #输出 30
wangcai.tooth = Dog.tooth
print(wangcai.tooth)  #输出 30

Dog.tooth = 40
print(Dog.tooth)      #输出 40
print(wangcai.tooth)  #输出 30
print(xiaohei.tooth)  #输出 40

# 类属性的优点 :
# 记录的某项数据 始终保持一致时,则定义类属性
# 实例属性要求每个对象为其单独开辟出一块内存空间来记录数据,而类属性为全类所共有
# 仅占用一份内存,更加节省内存空间

 

 

 

深入解析 Python 中的 super() 函数 ​super()​​​super()​​ 是一个强大的工具,可以简化父类方法的调用,并在多重继承中提供灵活性。通过使用 ​​super()​​,我们可以更好地控制方法解析顺序,并确保父类的构造函数和方法被正确调用。在编写可维护和可扩展的代码时,合理使用 ​​super()​​ 是非常重要的。 阅读详情

相关推荐

小红书x-mini签名逆向实战:Frida动态Hook与算法还原

在移动App协议分析中,请求签名机制是保障接口安全的核心技术,其本质是客户端对请求参数、时间戳、设备指纹等要素进行加密认证的过程。理解签名原理需掌握Native层加密流程、JNI调用机制及密钥动态派生逻辑。Frida作为主流动态插桩工具,能绕过符号剥离、字符串加密和控制流混淆等反分析手段,在函数执行瞬间捕获寄存器状态、内存数据与调用上下文,实现签名算法的完整还原。该技术广泛应用于合规内容监测、API自动化调用与竞品协议研究等工程场景。本文聚焦小红书x-mini签名这一典型样本,详解从JNI_OnLoad定位

weixin_31264565的博客 457

python中继承规则与super()的用法

python继承规则: 单下划线开头(_age): 表示protected保护变量属性或者方法,只可以被类和子类调用 双下划线开头(__age): 表示private私有属性或者方法更加苛刻,只可以类内部调用不可以被外部调用 super用法: 使用super()方法可以对继承的方法进行重写,但不覆盖父类方法,在多继承时作用较大,避免以菱形形状两次调用父类方法(多为构造的问题)。 1.对继承的方法重写: class Node(): ''' 父类 ''' def __init__(

m0_52785249的博客 208

MFC 利用soap 调用web service

MFC 利用soap 调用web service

congjiaoyan3682的博客 785

Python3:私有成员

目录 1.什么是私有成员 2.私有成员并非真正私有 3.私有函数调用方法 1.什么是私有成员 在Python里边,一个类的成员(成员变量、成员方法)是否为私有,完全由这个成员的名字决定。如果一个元成员的名字以两个下划线__开头,但不以两个下划线__结尾,则这个元素为私有的(private);否则,则为公有的(public)。Pyhton里边并没有protected的概念。 私有成员不以两个下划线结尾;所有的运算符重载相关方法,以一些特殊的成员方法如构造函数,都是以两个下划线开头,两个下划线结尾,

rs勿忘初心的博客 5502

集成电路模拟版图入门-版图基础学习笔记(四)

第三部分:版图的准备 2. 设计规则 3) Design Rule 2. 设计规则 4) 规则定义 4.1 NW(N WELL) 2. 设计规则 4) 规则定义 4.1 NW(N WELL) 2. 设计规则 4) 规则定义 4.2 PO(Poly) 2. 设计规则 4) 规则定义 4.3 M1(Metal1) 2. 设计规则 4) 规则定义 4.4 VIA 3. DRC文件 3.1 DRC:Design Rule Check,设计规则检查。 3.2 DRC程序了解有关

weixin_52955333的博客 6734

LangGraph实战:用Python异步构建智能客服多轮对话系统(附完整代码)

本文详细介绍了如何使用LangGraph框架和Python异步编程构建一个高性能的智能客服多轮对话系统。通过将对话流程建模为有向图,结合thread_id实现多用户对话隔离,并利用异步节点提升系统并发处理能力,有效解决了传统客服系统上下文遗忘与高并发瓶颈问题。文章提供了从环境搭建、状态管理、异步优化到复杂业务逻辑与部署的完整实战代码。

weixin_29055137的博客 149

python3 super_python3面向对象(2)之super()

super()是一个什么鬼?干什么用的?打开菜鸟教程看一下super()的简介;第一句话就是:super()函数是用来调用父类(超类)的一个方法。嗯哦;原来是一个函数可以返回一个父类的方法:于是我就这样理解了,那么如果是多继承呢,是返回所有父类的被调用的方法吗?一个疑问?看看下面的代码(先定义一个人类,然后定义一个男人,一个女人,一个儿子)class Person(object): #定义...

weixin_39773215的博客 91

TC3xx芯片中断配置避坑指南:从AUTOSAR Davinci配置到SRN地址计算的完整流程

本文详细解析了英飞凌TC3xx芯片的中断配置流程,从AUTOSAR Davinci工具链到硬件调试的全链路指南。重点介绍了中断路由(IR)模块、服务请求节点(SRN)和中断控制单元(ICU)的配置技巧,帮助开发者避开常见陷阱,优化中断性能。

weixin_30628801的博客 413

Python类:super

子类和父类有相同的方法,如果子类想调用父类的方法,可以使用super()方法

Python热爱者的博客 1952

STM32F4驱动ADS1220高精度ADC:从SPI配置到数据校准的完整实战指南

本文详细介绍了如何使用STM32F4微控制器驱动ADS1220高精度ADC,涵盖从SPI接口配置、寄存器设置到数据采集与校准的全过程。通过实战代码示例和硬件设计要点,帮助开发者快速构建高精度数据采集系统,适用于工业测量和精密仪器等应用场景。

weixin_26918763的博客 224

【STM32系统及仿真】基于STM32+蓝牙设计的智能窗帘系统__资料编号8

本项目设计并实现了一种基于STM32单片机的智能窗帘系统,集成了光敏传感器、温湿度传感器、蓝牙模块和OLED显示屏,实现了窗帘的自动调节、环境监测和远程控制功能。系统采用STM32F103C8T6作为主控制器,通过光敏传感器检测环境光强,温湿度传感器监测室内环境,蓝牙模块实现与手机APP的通信,用户可以通过APP远程控制窗帘的开合状态。系统在检测到环境光照强度或温度超出设定范围时,可自动调节窗帘的开合,以达到节能和提高舒适度的目的。

嵌入式阿齐Archie 2万+

python3 类super()

看例子很清晰,不写super,如果不定义子类的__init__属性,那么其实可以直接继承父类的属性和函数,见case1;不写super,如果定义子类的属性,那么无法继承父类的属性;如果写了super,就可以集成也可以自己写 一 class A: def __init__(self): self.a = 5 def fun_A(self): print("执行func_A") class B(A): # def __init__(self):

RUN 760

GB28181 —— 1、Ubuntu20.04下使用ZLMediaKit+WVP搭建GB28181流媒体监控平台(连接带云台摄像机)

GB28181 —— Ubuntu20.04下使用ZLMediaKit+WVP搭建GB28181流媒体监控平台

5460

Python基础(09)——面向对象

1.基本格式和使用 类: class 类名(): 代码块 对象: 对象名 = 类名() 2.组成 2.属性(特征) 实例属性: 修改:类外面 实例对象.属性名 = 值 类里面 self.属性名 = 值 获取:类外面 对象名.属性名 类里面 self.属性名 类属性:归属于类对象的属性,所有对象共有的属性 (类属性只能通过类对象修改,不能通过实例对象修改,如果通过实...

166

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

python 空对象模式_Python 面向对象基础

目录1. 类和 Java 一样,所有类都默认继承 object,object 是最顶层的父类。1.1 实例属性和类属性实例属性通过 self 关键字定义,类属性没有 self 修饰,直接写在类中。类属性一定要通过类名调用,不要使用对象名调用。例子如下:class A:aa = 1def __init__(self, x, y):self.x = xself.y = ya = A(2,3)A.aa ...

weixin_39936388的博客 212

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

详解Python中类属性、 实例属性、 类方法、 静态方法、实例方法以及super()的使用和单例模式

详解Python中类属性、 实例属性、 类方法、 静态方法、实例方法以及super()的使用和单例模式

渊雅 4035

一木.溪桥学Python-12:面向对象编程、私有属性、实例属性、类属性、封装、继承、单继承、super()

一木.溪桥 在Logic Education跟Amy学Python 逻辑教育 :https://logicedu.ke.qq.com 12期:Python基础课 一木.溪桥学Python-12:面向对象编程、私有属性、实例属性、类属性、封装、继承、单继承 、super() 日期:2021年1月11日 学习目标: 私有属性 类属性 封装 继承 单继承 super() 学习内容: 私有属性 私有属性与私有方法介绍 在实际开发中,对象的某些属性或者方法,只希望在对象的内部..

FaFrFu的博客 319

python类中super()

Python中类的初始化都是__init__(), 所以父类和子类的初始化方式都是__init__(), 但是如果子类初始化时没有这个函数,那么他将直接调用父类的__init__(); 如果子类指定了__init__(), 就会覆盖父类的初始化函数__init__(),如果想在进行子类的初始化的同时也继承父类的__init__(), 就需要在子类中显示地通过super()来调用父类的__init_...

shuijinghua的博客 1万+

python继承、多态---子类和父类、super()、派生、抽象类、多继承、多态特性

目录 一、继承特性 1.什么是继承? 2.继承中子类和父类的概念 3.继承的作用 4. 查看继承的父类 5.方法的复写 6.super() 7.__init__()方法 8.派生属性 9.私有属性私有方法在继承中的表现 10.抽象类 二、多继承 1、语法 3、继承原理(钻石继承) 4、多继承中super本质 三、多态特性 一、继承特性 1.什么是继...

优快云 9143

python面向对象3-多层继承、super()、私有权限、多态、类属性实例属性、类方法和静态方法

python面向对象3-多层继承、super()、私有权限、多态、类属性实例属性、类方法和静态方法

Sun123234的博客 489

python super()详解,一篇文章告诉你python的super是什么,如何使用

super()函数是用于调用父类(超类)的一个方法。本文首先引出了继承中存在的问题如何在子类调用父类的同名函数,然后引出c++和python做法,python中super的常见用法,super()两个参数的含义,super在多继承出现的问题。......

留下虚度光阴的一些证据。 5750

深入了解 Python 中的 super() 函数

super()函数用于调用父类的方法,在子类中可以使用super()来访问父类的属性和方法,从而实现对父类的调用和扩展。super()type是类名或类型名,用于指定要调用其父类的方法。是对象或类,用于指定要调用父类方法的对象或类。如果省略,会自动传入当前类和对象。super()函数是 Python 中一个非常强大和灵活的函数,用于调用父类的方法,特别是在多重继承的情况下。通过合理地应用super()函数,可以轻松地实现对父类方法的调用和扩展,使得代码更加灵活和易于维护。

GitHub_miao的博客 2585

本文带你完全掌握Python中super()函数的用法和原理

注意,这里的 self 也是当前 C 的实例,MRO 列表跟上面是一样的,搜索 A 在 MRO 中的下一个类,发现是 B,于是,跳到了 B 的 init,这时会打印出 enter B,而不是 enter Base。其实,在上面的情况下,super 获得的类刚好是父类,但在其他情况就不一定了,super 其实和父类没有实质性的关联。从上面的运行结果可以看出,基类Base的构造函数被调用了两次,这是有问题的,正常的应该是:A的构造函数调用一次,B的构造函数调用一次,基类Base的构造函数调用一次。

weixin_45841831的博客 4984

python 继承 面向对象三大特性 类属性和实例属性 类方法和静态方法

python 继承 面向对象三大特性 类属性和实例属性 类方法和静态方法

m0_72989992的博客 439

python super()函数

1.如果子类(Puple)继承父类(Person)不做初始化,那么会自动继承父类(Person)属性name。 2.如果子类(Puple_Init)继承父类(Person)做了初始化,且不调用super初始化父类构造函数,那么子类(Puple_Init)不会自动继承父类的属性(name)。 3.如果子类(Puple_super)继承父类(Person)做了初始化,且调用了super初始化了父类的构...

https://www.cnblogs.com/zpchcbd/ 3353

python高级编程学习——01—面对对象(鸭子类型、多态、抽象基类、isinstance和type的区别、类变量和对象变量、类属性和实例属性以及查找顺序、Python对象的自省机制、super函数)

1、深入类和对象:鸭子类型和多态 动态语言调用实例方法时不检查类型,只要方法存在,参数正确,就可以调用。这就是动态语言的“鸭子类型”,它并不要求严格的继承体系,一个对象只要“看起来像鸭子,走起路来像鸭子”,那它就可以被看做是鸭子。 a = [1, 2] b = [3, 4] c = (5, 6) # tuple类型 元祖 d = {7, 8} # 集合类型 set 它...

weixin_42118531的博客 334
上一篇: python 经典类和新式类
下一篇: python 异常
qiukapi
博客等级 码龄12年 51粉丝 93原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值