python方法的分类(实例方法、类方法、静态方法)

深入理解 Python 类中的各种方法 实例方法:绑定到实例,通过 self 访问实例属性和方法。类方法:绑定到类,通过 cls 访问和修改类属性。静态方法:不绑定到实例或类,通常用于逻辑上属于类但不依赖实例或类属性的方法。特殊方法:以双下划线包围,由 Python 在特定情况下自动调用。属性方法:将方法转换为属性,提供定制的 getter、setter 和 deleter。__new__ 方法:用于创建实例,在 __init__ 之前调用。__call__ 方法:使实例可以像函数一样被调用。__del__ 方法。 阅读详情
方法和函数的区分

很多童鞋会比较疑惑,方法和函数有什么区别,都是通过def去定义的啊?
只需要记住一点,方法是用来描述一个目标的行为动作!
不论你是直接通过 类名.方法调用,还是通过由类生成的实例.方法调用。
方法都需要有一个目标才能完成调用的操作。

方法分类

谈到python的方法,很多人认为就是一个class 然后跟你的方法名称就完了,哪有什么分类?
最开始学类的时候我也是这么认为,并且很多的入门书中也没有提及这些。
那么,到底方法分为哪几类呢?
让我们先来看一段代码

class MainClass:
    def shilifangfa(self):
        print('这是一个实例方法')

    @classmethod
    def leifangfa(cls):
        print('这是一个类方法')
    @staticmethod
    def jingtaifangfa():
        print('这是一个静态方法')

m=MainClass()
m.shilifangfa()
m.leifangfa()
m.jingtaifangfa()

output:
这是一个实例方法
这是一个类方法
这是一个静态方法

好吧,先说下方法的分类吧:

  1. 实例方法
  2. 类方法
  3. 静态方法
初步展示方法的区别

可是,这三种方法有什么区别呢,光看上面的这段代码,没有任何差异啊。
那么我们把这段代码稍作修改

class MainClass:
    def shilifangfa(self):
        print('这是一个实例方法',self)

    @classmethod
    def leifangfa(cls):
        print('这是一个类方法',cls)
    @staticmethod
    def jingtaifangfa():
        print('这是一个静态方法')

m=MainClass()
m.shilifangfa()
m.leifangfa()
m.jingtaifangfa()
output:
这是一个实例方法 <__main__.MainClass object at 0x00000000012AF0B8>
这是一个类方法 <class '__main__.MainClass'>
这是一个静态方法

这次的输出和上次相比,是否看到实例方法,我们需要传给它一个实例对象,而类方法我们需要传给他的是一个类
那么如果我们给实例方法传输的不是一个由类产生的实例会如何呢?

MainClass.shilifangfa()
TypeError: shilifangfa() missing 1 required positional argument: 'self'

报错的意思很明显,我们需要传给他一个实例的名称,当然你也可以随便写一个数值去传递,那么也就没有作为实例方法的意义了
说了实例方法,那么类方法呢?同样我们换一种方式去调用

MainClass.leifangfa()
这是一个类方法 <class 'main.MainClass'>

实例方法与类方法的细化区别

这次没有任何变化,为什么呢?
原因在于,当使用类方法时,传递的参数应该是一个类名,但如果是实例,系统会自动找到实例对应的类名称
仔细看看下面的代码,你会对实例方法与类方法有更详细的认识

class MainClass:
    a=100 # 方法本身的属性
    def shilifangfa(self):
        print('这是一个实例方法',self.a)
        print(self.index) # 正常访问
        self.a=200 # 相当于实例本身创建了一个属性
        print(self.a) # output a=200
        print(MainClass.a) # output a=100


    @classmethod
    def leifangfa(cls):
        print(cls.index) # type object 'MainClass' has no attribute 'index'
        # 注意这句type object 它变相的告诉你,类也是一个对象,只不过是一个type的对象
        # 这就更验证了python中的那句,万物皆对象
        print('这是一个类方法',cls.a)
        cls.a = 200 # 修改了类本身的a
        print(cls.a)  # output a=200
        print(MainClass.a) # output a=200
        # print(cls.index) # 类方法无法获取到实例的属性
    @staticmethod
    def jingtaifangfa():
        print('这是一个静态方法')

m=MainClass()
m.index=1000 # 实例本身的属性
m.shilifangfa()
MainClass.leifangfa()
m.jingtaifangfa()

©本文由简书作者:清风Python 原创 如需转载请注明

python中 一个区分类属性,实例属性,静态方法,类方法,实例方法的案例 (Python经典编程案例) 代码如下: class Game(object): # 历史最高分 top_score = 0 def __init__(self, player_name): self.player_name = player_name @staticmethod def show_help(): print("帮助信息:让僵尸进入... 阅读详情

相关推荐

AI 小说生成器本地部署完全指南

这篇文章介绍了本地部署AI小说生成器的完整指南,主要面向网文作者、内容创作者和AI爱好者。文章从环境搭建到创作实践,详细讲解了三种主流部署方案:Ollama(推荐新手)、LMStudio(图形界面)和text-generation-webui(高级定制)。内容涵盖硬件需求、系统架构、模型选择、API对接、提示词工程等关键技术环节,并提供了小说创作的特制提示词模板和参数调优建议。文章还讨论了长篇小说管理、多模型协作等进阶技巧,以及版权伦理等法律问题。最后推荐了相关工具资源和社区论坛,帮助读者实现安全、高效、可

珂珂可爱多 2390

Python中方法的分类

按所属类别实例方法、类方法、静态方法。按功能构造方法、析构方法、普通方法、魔术方法。按访问权限公共方法、保护方法、私有方法。不同类型的方法用于不同的目的,根据类的需求,可以选择适合的方法类型。

weixin_43414019的博客 1294

Flowable多数据源实战:从配置到指定Schema的避坑指南

本文详细介绍了Flowable多数据源配置的实战指南,包括基础配置、数据源Bean创建、指定Schema的进阶配置以及常见问题排查。通过具体代码示例和避坑建议,帮助开发者高效实现多租户系统中的工作流引擎集成,特别强调了schema设置和事务管理的注意事项。

weixin_30824599的博客 489

【python】类里面可以定义哪几种方法?

在Python中,类是一个用于创建对象的模板或蓝图。类可以包含数据(属性)和方法,这些方法定义了对象的行为。Python中的类方法可以根据其用途和访问级别进行分类,包括实例方法、类方法、静态方法、特殊方法(或“魔术”方法)、以及以单个下划线开头的方法。下面是对这些方法的介绍。

MAOZI8的博客 1153

使用petalinux做嵌入式设计开发(1)

1.创建vivado工程,建立硬件环境,最终导出hdf文件 既可以在windows系统下的vivado上编写硬件工程并导出hdf文件,也可以在linux系统下的vivado中编写硬件工程并导出hdf文件。(对于windows系统下导出的hdf文件还需要传递到linux系统下的文件夹中。) 2.以hdf硬件文件为基础创建,配置,编译,打包petalinux工程,导出linux系统所需镜像文件。 具体步骤: (0)设置环境变量 设置环境变量使得我们可以直接使用petalin...

plotup的博客 2083

逆向实战:从x-mini签名到RPC调用,Frida动态分析小红书加密协议

本文通过实战案例,详细拆解了小红书App的加密协议逆向分析过程。从识别x-mini签名等关键参数入手,结合静态分析与Frida动态Hook技术,追踪到核心的RPC调用入口,并最终封装成可独立调用的RPC函数,为安全研究和协议理解提供了完整的技术路径。

moss5的博客 1064

python——实例方法、静态方法和类方法区别

一、python 类语法中有三种方法,实例方法,静态方法,类方法 python中self,cls的区别: 普通实例方法,第一个参数需要是self,它表示一个具体的实例本身。 如果用了staticmethod,那么就可以无视这个self,而将这个方法当成一个普通的函数使用。 而对于classmethod,它的第一个参数不是self,是cls,它表示这个类本身。 实例方法只能被实例对象调用,静态...

u012114090的博客 512

无需Root!安卓模拟器+BurpSuite轻松搞定微信小程序抓包

本文详细介绍了如何在不root安卓设备的情况下,使用安卓模拟器和BurpSuite实现微信小程序抓包。通过夜神模拟器降级安卓版本、配置BurpSuite代理及安装证书等步骤,开发者可以轻松绕过微信的证书绑定,高效抓取小程序数据包。文章还提供了常见问题排查和高阶技巧,帮助开发者提升抓包效率。

weixin_29213655的博客 370

Python类的多种方法,你分得清吗?

在初学Python过程中,会遇到这样的概念,一个类下面会有多个方法,有的叫类方法、有的叫静态方法,还有的叫实例方法。当调用他们的时候,不免会有点蒙圈,那么他们之间的区别是什么呢?

weixin_56659172的博客 991

Autosar诊断实战系列23-NRC优先级解析

NRC分类,优先级判断逻辑及测试注意事项介绍。

initiallizer的博客 2628

基于YOLOv8/YOLOv7/YOLOv6/YOLOv5的农作物害虫检测系统(深度学习模型+UI界面+训练数据集)

随着人工智能技术在农业领域的深入应用,基于深度学习的害虫检测系统已成为智慧农业的重要组成部分。本文详细介绍了一种基于YOLOv8/YOLOv7/YOLOv6/YOLOv5的农作物害虫检测系统,涵盖算法原理、数据集构建、模型训练、系统实现及完整代码。该系统能够实时检测并识别多种农作物害虫,为农业生产提供精准的病虫害监测解决方案。

YOLO 276

python类中的方法分类_python方法的分类(实例方法、类方法、静态方法)

方法和函数的区分很多童鞋会比较疑惑,方法和函数有什么区别,都是通过def去定义的啊?只需要记住一点,方法是用来描述一个目标的行为动作!不论你是直接通过 类名.方法调用,还是通过由类生成的实例.方法调用。方法都需要有一个目标才能完成调用的操作。方法分类谈到python的方法,很多人认为就是一个class 然后跟你的方法名称就完了,哪有什么分类?最开始学类的时候我也是这么认为,并且很多的入门书中也没有...

weixin_39576294的博客 563

Prometheus+Grafana+alertmanager+PrometheusAlert监控告警 实现飞书告警

以上 是以grafana做的邮件告警,但是感觉邮件很少人看。下面是以webhook 可以接入。启动alertmanager (设置 开机在启动)下载prometheusalter 配置文件。这里的告警是基于grafana上搭建的。我们启动PrometheusAlert。写完之后进行重启Prometheus。prometheus 的告警规则。测试 基于我们生产环境做的文档。然后在grafana上导模板。上导入模板就可以 直接引用。访问 grafana页面。重启一下grafana。

墨痕诉清风的博客 874

python中实例方法分类_python方法的分类(实例方法、类方法、静态方法)

方法和函数的区分很多童鞋会比较疑惑,方法和函数有什么区别,都是通过def去定义的啊?只需要记住一点,方法是用来描述一个目标的行为动作!不论你是直接通过 类名.方法调用,还是通过由类生成的实例.方法调用。方法都需要有一个目标才能完成调用的操作。方法分类谈到python的方法,很多人认为就是一个class 然后跟你的方法名称就完了,哪有什么分类?最开始学类的时候我也是这么认为,并且很多的入门书中也没有...

weixin_33344572的博客 128

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

python 实例方法_python方法的分类(实例方法、类方法、静态方法)

方法和函数的区分很多童鞋会比较疑惑,方法和函数有什么区别,都是通过def去定义的啊?只需要记住一点,方法是用来描述一个目标的行为动作!不论你是直接通过 类名.方法调用,还是通过由类生成的实例.方法调用。方法都需要有一个目标才能完成调用的操作。方法分类谈到python的方法,很多人认为就是一个class 然后跟你的方法名称就完了,哪有什么分类?最开始学类的时候我也是这么认为,并且很多的入门书中也没有...

weixin_39889788的博客 63

深度学习工具包 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")

python中实例方法分类_荐Python 类中的方法分类以及特点详解 [OOP][实例方法][类方法][静态方法][方法的调用方式][实例方法的“绑定”调用方式][实例方法的“非绑定”调用方式]...

您的“关注”和“点赞”,是信任,是认可,是支持,是动力…如意见相佐,可留言。本人必将竭尽全力试图做到准确和全面,终其一生进行修改补充更新。1 Python 类中的方法分类概述实例方法:在类中定义的方法通常默认都是实例方法,包括构造方法。类方法:至少要有一个形式参数,通常命名为 cls,Python 会自动将类本身(注意:不是类对象)绑定给 cls 参数,无需显式为 cls 传参;并且类方法需要用 ...

weixin_39795284的博客 185

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

python中类方法与实例方法的区别-Python实例方法、静态方法和类方法详解(包含区别和用法)...

和类属性一样,类方法也可以进行更细致的划分,具体可分为类方法、实例方法和静态方法。和类属性的分类不同,对于初学者来说,区分这 3 种类方法是非常简单的,即采用 @classmethod 修饰的方法为类方法;采用 @staticmethod 修饰的方法为静态方法;不用任何修改的方法为实例方法。其中 @classmethod 和 @staticmethod 都是函数装饰器,后续章节会对其做详细介绍。接...

weixin_37988176的博客 88

Python中的实例方法、静态方法和类方法三者区别?

不用@classmethod和@staticmethod修饰的方法为实例方法。在类中定义的方法默认都是实例方法。实例方法最大的特点是它至少要包含一个self参数,用于绑定调用此方法的实例对象,实例方法通常可以用类对象直接调用。采用修饰的方法为类方法。类方法和实例方法相似,它至少也要包含一个参数,只不过类方法中通常将其命名为cls,Python会自动将类本身绑定给cls参数。我们在调用类方法时,无需显式为cls参数传参。

qq_41081716的博客 574

Python——property函数、类方法和静态方法以及描述符

counter = 0 # 类变量cls.counter += 1 # 修改类变量# 调用类方法MyClass.increment() # 输出: Counter is now: 1MyClass.increment() # 输出: Counter is now: 2在这个例子中,increment是一个类方法,它通过装饰器来定义。这个方法简单地递增了类变量counter的值,并打印出当前的计数值。注意,由于这是一个类方法,它接收cls。

weixin_45720999的博客 1605
上一篇: python 时间模块 time datetime calendar
下一篇: python原类、类的创建过程与方法
清风Python
博客等级 码龄7年 406粉丝 267原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址