__str__输出类

Python输出格式全总结_python write函数 格式控制 str()函数是用于返回人类可读的值的表示,而repr()是用于生成解释器可读的表示(如果没有等效的语法,则会强制执行SyntaxError)对于没有人类可读性的表示的对象,str()将返回和repr()一样的值。你仍将使用 { 和 } 来标记变量将被替换的位置,并且可以提供详细的格式化指令,但你还需要提供要格式化的信息。string模块包含一个Template类,它提供了另一种将值替换为字符串的方法,使用类似$x的占位符并用字典中的值替换它们,但对格式的控制要少的多。这样可以更好地控制值的格式化方式。 阅读详情
class Cat:
    """定义一个猫类"""
 
    def __init__(self, new_name, new_age):
        """在创建完对象之后 会自动调用, 它完成对象的初始化的功能"""
        # self.name = "汤姆"
        # self.age = 20
        self.name = new_name
        self.age = new_age  # 它是一个对象中的属性,在对象中存储,即只要这个对象还存在,那么这个变量就可以使用
        # num = 100  # 它是一个局部变量,当这个函数执行完之后,这个变量的空间就没有了,因此其他方法不能使用这个变量
 
    def __str__(self):
        """返回一个对象的描述信息"""
        # print(num)
        return "名字是:%s , 年龄是:%d" % (self.name, self.age)
 
    def eat(self):
        print("%s在吃鱼...." % self.name)
 
    def drink(self):
        print("%s在喝可乐..." % self.name)
 
    def introduce(self):
        # print("名字是:%s, 年龄是:%d" % (汤姆的名字, 汤姆的年龄))
        # print("名字是:%s, 年龄是:%d" % (tom.name, tom.age))
        print("名字是:%s, 年龄是:%d" % (self.name, self.age))
 
# 创建了一个对象
tom = Cat("汤姆", 30)
print(tom)
Python类中内置方法__str__详解 如果我们想要在子类中重写__str__方法,则可以使用super()函数调用父类中的__str__方法,并在其后附加子类特有的信息。在子类中,我们重写了__str__方法,并使用super()函数调用父类的__str__方法,然后添加了子类特有的信息。当我们这样做时,我们可以使用super()函数来调用父类中的__str__方法,然后在其后添加子类特有的信息。在上述代码中,我们定义了一个类Person,其中包含了一个__str__方法来打印类的实例。__str__方法的重写。__str__的作用。 阅读详情

相关推荐

unity游戏开发日志(一)将mmd模型导入unity,并解决材质丢失的问题

unity音乐游戏开发,导入角色模型并解决材质问题

yizhigou1的博客 1765

python之实战str引入输出几种方式

上一篇:Python函数摘要篇(几种形参方式,局部变量问题,递归等) 点击跳转 目录篇:python相关目录篇 点击跳转 下一篇:Python之实战装饰器拆解 点击跳转  目录 字符串取变量名 #''''''+字变量+''''''方式取变量 #%方式取变量(%d是要求取的变量是int整数) #.format格式化取变量 #变量需注意(Python一切皆对象): #%s其他功能 字符串...

Burgess_zheng的博客 1319

lvgl 实现表格table,并且固定表头

嵌入式实现table,lvgl 实现原生表格table组件

m0_61704502的博客 1273

python(54)-str格式化输出

#1.设定位置和不设定位置 >>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world' 2.

aggie4628的专栏 1778

【AI智能体】Hermes Agent 从部署到项目实战操作详解

Hermes Agent 桌面版从安装到实战操作详解

congge 5147

实战17:GCN+LSTM图卷积神经网络预警预测 完整代码数据集

实战17:GCN+LSTM图卷积神经网络预警预测 完整代码数据集

1947

printf如何输出string类型,及c_str()函数部分要点

要点: printf只能输出C语言内置的数据,而string不是内置的,只是一个扩展的类,直接输出肯定是错误的! 其实方法很简单只需用如下函数就可将其输出: string test = "测试代码段"; printf("%s",test.c_str()); 调用c_str()函数即可进行输出,同时使用cout也可以输出。 下面是关于c_str()函数的几点说明: 1.c_str()函数返回一个指向正规c字符串的指针,内容和string类的本身对象是一样的,通过string类的c_str()函数

Charles_Clark的博客 6412

基于毫米波雷达的智能风扇算法设计与实现

摘要:本文设计了一种基于毫米波雷达的智能风扇控制系统,采用FMCW雷达实现人体目标的精准检测与定位。系统通过距离FFT、速度FFT、CFAR检测和AoA估计构建完整的信号处理链路,并针对风扇叶片干扰设计了基于自相关函数的抗干扰算法。创新性地提出了人在开机、多人优先送风、摇头追踪等控制策略。研究采用MATLAB完成全链路算法仿真验证,并在STM32平台上实现实物系统。实验表明,该系统可实现0.15m测距精度和±60°方位角覆盖,有效解决了传统风扇的能源浪费和用户体验问题。本文提供了完整的MATLAB仿真代码和

huanghm88的专栏 405

python——类和对象之__str__方法的使用

用于返回一个对于”对象的描述“,对应于内置函数str()经常用于print()方法,帮我们查看对象的信息,所以我们经常会对__str__()方法进行重写 运行结果为: 同学的名字kb,年龄18 当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据 __str__方法需要返回一个字符串,当做这个对象的描写 ...

python全栈 1143

3步!Spring Boot+OCR引擎秒提身份证/营业执照?手把手教你从零实现!

OCR技术革新文档识别效率 本文演示了如何利用Spring Boot+Tesseract OCR+OpenCV构建自动化文档识别系统。相比传统人工录入,OCR技术可实现: 5秒极速提取身份证/营业执照关键信息 精准识别中文文本(准确率90%+) 正则过滤自动匹配结构化数据 技术要点: OpenCV图像预处理(灰度化+二值化) Tesseract多语言OCR识别 正则表达式精准提取证件号码 效率提升达100倍,错误率降低90%,适用于金融、政务等需要批量处理证件的场景。

java专栏 906

10、贝叶斯曲线拟合与预测分布详解

本文详细介绍了贝叶斯曲线拟合与预测分布的核心概念与计算方法。从最大似然估计出发,引入参数的先验分布,推导出后验分布与最大后验估计,并进一步展示如何通过积分获得完整的预测分布。文章解析了预测分布中均值与方差的构成,强调贝叶斯方法在量化不确定性方面的优势,涵盖金融、医疗、气象等实际应用场景。最后总结了操作步骤与未来研究方向,帮助读者系统掌握贝叶斯方法在回归问题中的应用。

android的专栏 106

python-------__str__()方法

代码—————————— """ 什么是__str__方法? 在python中,使用print()输出对象是获得了引用对象是由那个创建的对象与对象的地址值 而要想输出其它自定义内容是就可以使用str方法了 注意!str方法必须返回一个字符串 """ class Cat(): def __init__(self,new_name): self.name=new_name print("%s 来了"%self.name) def __del__(

本人是新手,有一定的了解不到位,望海涵 192

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

Python类中的__str__方法:让你的调试输出更优雅的3个技巧

本文深入探讨了Python类中__str__方法的3个进阶技巧,帮助开发者提升调试效率与代码可读性。首先明确区分__str__与__repr__的黄金法则,其次讲解如何动态格式化复杂对象与嵌套结构,最后分享面向生产环境的高级实践与性能避坑指南,让你的对象输出既优雅又实用。

weixin_29094979的博客 428

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

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

python str对象的方法_Python __str__() 方法

str__方法和__init__方法类似,都是一些特殊方法,所以前后都有双下划线,它用来返回对象的字符串表达式 如果要把一个类的实例变成 str,就需要实现特殊方法__str():不使用__str__()方法class Student(object):def __init__(self,id,name,age):self.id=idself.name=nameself.age=ages=Stude...

weixin_28951683的博客 1262

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

python中str怎么求和_Python __str__() 方法

str__方法和__init__方法类似,都是一些特殊方法,所以前后都有双下划线,它用来返回对象的字符串表达式 如果要把一个类的实例变成 str,就需要实现特殊方法__str():不使用__str__()方法class Student(object):def __init__(self,id,name,age):self.id=idself.name=nameself.age=ages=Stude...

weixin_34044889的博客 1023

Python 面向对象 类 __str__

class dog(object): def __init__(self,name): self.name = name d = dog('mike') print(d) # <__main__.dog object at 0x00000000026BE940> 不想让他这样显示 如果一个类中定义了__str__方法,...

weixin_30480583的博客 160

python重写str_第8.16节 Python重写自定义类的__str__方法

一、引言上节结合案例介绍了重写__repr__方法的关注点,重写__repr__方法的要点是要准确的输出开发人员关注的信息,并便于开发人员使用相关信息。而__str__方法是为最终用户返回类的相关信息,因此需要相关信息容易理解,更需要开发者在自定义类的过程中重写__str__方法。object类提供的__str__方法,只是简单输出模块名、类名以及对象的ID信息,老猿认为实际上就是在__str__...

weixin_29247219的博客 306

Python类的__str__()方法

如果要把一个类的实例变成 str,就需要实现特殊方法__str__(): 不使用__str__()方法 class Student(object): def __init__(self,id,name,age): self.id=id self.name=name self.age=age s=Student(111,"Bob",18...

LinRuiC的博客 8375

python 类的__str__方法

转载自文章:str()方法 当使用print输出对象的时候,只要类中自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据。 例如: class Cat: """定义一个猫类""" def __init__(self, new_name, new_age): """在创建完对象之后 会自动调用, 它完成对象的初始化的功能""" # self.name = "汤姆" # self.age = 20

qq_39579500的博客 1805

Python习题 168:定义图书类的打印和输出

两个特殊方法,分别用于定制对象的字符串表示形式。在示例用法中,我们创建了一个 Book 实例,并演示了如何通过 print 和 repr 来观察不同的输出格式。请编写 Book 类的代码,并演示其使用。这个例子中,Book 类包含了。

2202_76035290的博客 305

python类中str_实例详解python定制类__str__

python定制类__str__(实例详解)在以下的文章之中我们来了解一下什么是python中的定制类。了解一下什么是python定制类,以及python定制类在python编程之中能起到什么样的作用。看到类似__slots__这种形如__xxx__的变量或者函数名就要注意,这些在Python中是有特殊用途的。__slots__我们已经知道怎么用了,__len__()方法我们也知道是为了能让cla...

weixin_39973009的博客 139

__str__在python中的用法__str_如何在python中进行重载?

我们面对一些相似的事物时,可以想给它们定义一个名称。为了能在日后的使用中不会混淆,可以加入参数进行区分,这就是对于重载的理解。今天同样为大家继续讲述魔法函数中的内容,常见的_str_的使用想必大家已经学过了,这里我们就_str_在python中进行重载的方法给大家带来分享。1、str函数,会 return一个字符串2、当调用print函数,传入一个类的实例,这个类里面定义了_str_函数,这时候就...

weixin_39603327的博客 731

定义一个类STR

类str

qq_41481008的博客 355

Stirng类的常见用法:输出str长度,输出第一个"o",和最后一个"o"的索引,将str中的字符"l"替换成"m",字符串str按空格“ ”分割为2个字符串,比较这两个字符串是否相等。

String类的常用方法 String str = "Hello World"; 输出str长度 输出第一个"o",和最后一个"o"的索引 将str中的字符"l"替换成"m" 字符串str按空格“ ”分割为2个字符串,比较这两个字符串是否相等。

普罗旺斯_浅笑的博客 1648

Python3中__str__方法的作用

当使用print输出对象的时候,若定义了__str__(self)方法,打印对象时就会从这个方法中打印出return的数据。__str__方法用例: class Person: """ 定义一个人“类” """ def __init__(self,name,weight): self.name = name self.weight =...

Vy小港的专栏 1万+
上一篇: python迭代器
下一篇: 倒遍历python
普通网友
博客等级 码龄6年 137粉丝 103原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值