Python的其他方法

1 __str__方法

  • 触发时机: 使用print(对象)或者str(对象)的时候触发
  • 功能: 查看对象信息
  • 参数: 一个self接受当前对象
  • 返回值: 必须返回字符串类型

基本用法

创建一个基本的类

class Cat():
gift = "catch mouse"
def __init__(self,name):
self.name = name
def cat_info(self):
strvar = "This object is {},and cat can catch {} normally".format(self.name,self.gift)
return strvar
tom = Cat("Tom")
res = tom.cat_info()
print (res)
print (tom)

使用__str__定义属性查看

class Cat():
gift = "catch mouse"
def __init__(self,name):
self.name = name
def cat_info(self):
strvar = "This object is {},and cat can catch {} normally".format(self.name,self.gift)
return strvar
def __str__(self):
return "strcgdfas" #必须要返回一个字符串 tom = Cat("Tom")
res = tom.cat_info()
print (res)
print (tom)

不返回字符串报错

class Cat():
gift = "catch mouse"
def __init__(self,name):
self.name = name
def cat_info(self):
strvar = "This object is {},and cat can catch {} normally".format(self.name,self.gift)
return strvar
def __str__(self):
return 1234 tom = Cat("Tom")
res = tom.cat_info()
print (res)
print (tom)

执行

可与i调用函数,世界返回信息

class Cat():
gift = "catch mouse"
def __init__(self,name):
self.name = name
def cat_info(self):
strvar = "This object is {},and cat can catch {} normally".format(self.name,self.gift)
return strvar
def __str__(self):
return self.cat_info() tom = Cat("Tom")
res = tom.cat_info()
print (res)
print (tom)

执行

[root@node10 python]# python3 test.py
This object is Tom,and cat can catch catch mouse normally
This object is Tom,and cat can catch catch mouse normally

2 __repr__方法

  • 触发时机: 使用repr(对象)的时候触发
  • 功能: 查看对象,与魔术方法__str__相似
  • 参数: 一个self接受当前对象
  • 返回值: 必须返回字符串类型

实例

class Mouse():
gift = "make holes"
def __init__(self,name):
self.name = name
def mouse_info(self):
strvar = "This object is {},and mouse can {} normally".format(self.name,self.gift)
return strvar
def __repr__(self):
return self.mouse_info() jerry = Mouse("Jerry")
res = repr(jerry)
print (res)
print (jerry) #这里是因为相当于执行__str__ = __repr__,把一个函数赋给另一个函数,在底层自己实现,把删除当做变量名使用
#也可以强转,效果一样
res = str(jerry)
print (res)

执行

[root@node10 python]# python3 test.py
This object is Jerry,and mouse can make holes normally
This object is Jerry,and mouse can make holes normally
This object is Jerry,and mouse can make holes normally

把函数当作变量名使用

def func():
print("只是一个函数")
func2 = 5
func2 = func
func2()

执行

[root@node10 python]# python3 test.py
只是一个函数

3 __bool__ 魔术方法

类似的还有如下等等(了解):
__complex__(self) 被complex强转对象时调用
__int__(self) 被int强转对象时调用
__float__(self) 被float强转对象时调用
  • 触发时机:使用bool(对象)的时候自动触发
  • 功能:强转对象
  • 参数:一个self接受当前对象
  • 返回值:必须是布尔类型
class MyClass():
def __bool__(self):
return False
obj = MyClass()
res = bool(obj)
print (res)

执行

[root@node10 python]# python3 test.py
False

不是布尔值,使用数字报错

class MyClass():
def __bool__(self):
return 1
obj = MyClass()
res = bool(obj)
print (res)

执行

4 __add__ 魔术方法

与之相关的__radd__ 反向加法
类似的还有如下等等(了解):
__sub__(self, other) 定义减法的行为:-
__mul__(self, other) 定义乘法的行为:
__truediv__(self, other) 定义真除法的行为:/
  • 触发时机:使用对象进行运算相加的时候自动触发
  • 功能:对象运算
  • 参数:二个对象参数
  • 返回值:运算后的值

对象直接相加不支持

class MyClass():
pass
obj = MyClass()
res = obj +2

执行

使用__add__和__radd__方法

class MyClass():
def __init__(self,num):
self.num = num
def __add__(self,other):
# self 自动接收对象,other是另外一个值
# 当对象在+加号左侧的时候,自动触发
return self.num *3 +other
#当对象在+的右侧,自动触发
def __radd__(self,other):
return self.num*2+other
obj = MyClass(5)
res = obj +2
print (res) res = 3 + obj
print (res)

执行

[root@node10 python]# python3 test.py
17
13

对象加对象

class MyClass():
def __init__(self,num):
self.num = num
def __add__(self,other):
# self 自动接收对象,other是另外一个值
# 当对象在+加号左侧的时候,自动触发
return self.num *3 +other
#当对象在+的右侧,自动触发
def __radd__(self,other):
return self.num*2+other
obj1 = MyClass(5)
res = obj1 +2
print (res) obj2 = MyClass(3)
res = 3 + obj2
print (res) res = obj1 + obj2
print (res)

执行

[root@node10 python]# python3 test.py
17
9
21

执行过程

obj1在加号的左侧,先执行add方法
res = obj1 + obj2
self接收的是obj1对象other接收的是obj2对象
return self.num + other相当于 obj1.num*3 + obj2 = 15 + obj2
res = 15 + obj2
对象obj2在+号右侧,触发radd
self接收对象obj2,other节后对象15
eturn self.num + other相当于obj2.num*2+ 15 =3*2 + 15 =21
return 21
res = 21

5 __len__  魔术方法

  • 触发时机:使用len(对象)的时候自动触发
  • 功能:用于检测对象中或者类中成员个数
  • 参数:一个self接受当前对象
  • 返回值:必须返回整型

给你一个对象,算出该对象所归属的类里面有几个自定义成员.

listvar = [1,2,3,4,5]
res = len(listvar)
print(res) class MyClass():
pty1 = 1
pty2 = 2
__pty3 = 3
__pty4 = 4 def func():
pass
def func2():
pass
def __func3():
pass
def __func4():
pass
res = MyClass.__dict__
print (res)
obj = MyClass()

执行

[root@node10 python]# python3 test.py
5
{'__module__': '__main__',
'pty1': 1, 'pty2': 2,
'_MyClass__pty3': 3,
'_MyClass__pty4': 4,
'func': <function MyClass.func at 0x7fcaf74880d0>,
'func2': <function MyClass.func2 at 0x7fcaf7488158>,
'_MyClass__func3': <function MyClass.__func3 at 0x7fcaf74881e0>,
'_MyClass__func4': <function MyClass.__func4 at 0x7fcaf7488268>,
'__dict__': <attribute '__dict__' of 'MyClass' objects>,
'__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None}

使用len方法

listvar = [1,2,3,4,5]
res = len(listvar)
print(res) class MyClass():
pty1 = 1
pty2 = 2
__pty3 = 3
__pty4 = 4 def func():
pass
def func2():
pass
def __func3():
pass
def __func4():
pass def __len__(self):
res = MyClass.__dict__
#以__开头和以__结尾的都不要使用not
          lst = [i for i in res if not ( i.startswith("__") and i.endswith("__")) ]
# print(lst)
return len(lst) res = MyClass.__dict__
obj = MyClass()
res = len(obj)
print(res)

执行

[root@node10 python]# python3 test.py
5
8

034.Python的__str__,__repr__,__bool__ ,__add__和__len__魔术方法的更多相关文章

  1. 零基础小白Python入门必看:面向对象之典型魔术方法

  2. python基础知识09-继承,多继承和魔术方法

    1.继承 class Father: def init(self,age,sex): self.age = age self.sex = sex class Son(Father): 类名后面写括号, ...

  3. Python 魔术方法指南

    入门 构造和初始化 构造定制类 用于比较的魔术方法 用于数值处理的魔术方法 表现你的类 控制属性访问 创建定制序列 反射 可以调用的对象 会话管理器 创建描述器对象 持久化对象 总结 附录 介绍 此教 ...

  4. Python 基础之面向对象之常用魔术方法

    一.__init__魔术属性 触发时机:实例化对象,初始化的时候触发功能:为对象添加成员,用来做初始化的参数:参数不固定,至少一个self参数返回值:无 1.基本用法 #例:class MyClass ...

  5. python面对对象编程------4:类基本的特殊方法__str__,__repr__,__hash__,__new__,__bool__,6大比较方法

    一:string相关:__str__(),__repr__(),__format__() str方法更面向人类阅读,print()使用的就是str repr方法更面对python,目标是希望生成一个放 ...

  6. python 中的 %s,%r,__str__,__repr__

    1.%s,%r的区别 在进行格式化输出时,%r 与 %s 的区别就好比 repr() 函数处理对象与 str() 函数处理对象的差别. %s ⇒ str(),比较智能: %r ⇒ repr(),处理较 ...

  7. python基础---- __getattribute__----__str__,__repr__,__format__----__doc__----__module__和__class__

    目录: 一. __getattribute__ 二.__str__,__repr__,__format__ 三.__doc__ 四.__module__和__class__ 一. __getattri ...

  8. Python的程序结构[1] -> 方法/Method[4] -> 魔术方法 __call__ / __str__ / __repr__

    __call__ 方法 __call__ 是当对象被调用时会调用的方法,允许一个对象(类的实例等)像函数一样被调用,也可以传入参数. 1 class Foo(): 2 def __init__(sel ...

  9. python的__call__、__str__、__repr__、__init__、__class__、__name___、__all__、__doc__、__del__等魔术方法的作用

    python中,一切都是对象 在Python中,所有以“__”双下划线包起来的方法,都统称为“Magic Method”--魔术方法 1.__call__:作用是把类实例变成一个可调用对象 在Pyth ...

随机推荐

  1. 201871030115-康旭 实验三 结对项目—《D{0-1}KP 实例数据集算法实验平台》项目报告

    项目 内容 课程班级博客链接 18卓越班 这个作业要求链接 实验三结对编程要求 我的课程学习目标 (1)体验软件项目开发中的两人合作,练习结对编程(Pair programming):(2)掌握Git ...

  2. OO第三单元小结

    目录 JML理论基础 JML工具链 openjml使用 openjml总结 jmlunitng使用 代码分析 第一次作业 第二次作业 第三次作业 测试&bug分析 黑盒测试 白盒测试(Juni ...

  3. 记docker安装和ida远程调试问题

    docker安装 1.卸载可能存在的旧版本: sudo apt-get remove docker docker-engine docker-ce docker.io   如果想要彻底卸载docker ...

  4. JAVA JNI 中解决在C/C++跨线程FindClass失败

    在JAVA与C/C++交互时使用JNI接口: 先是在JAVA调用的C++方法中直接测试FindClass,使用获取到的jclass操作没有任何问题: 但是在调用的C++方法中起线程后,在线程中Find ...

  5. 代码安全丨第六期:XPath注入漏洞样例

    1.什么是XPath注入漏洞? XPath是一种用来在内存中导航整个XML树的语言,它使用路径表达式来选取XML文档中的节点或者节点集. XPath注入是指程序使用外部输入动态构造用于从XML数据库检 ...

  6. 通读《构建之法》与CI/CD工具尝试

    项目 内容 这个作业属于哪个课程 2021春季软件工程(罗杰 任健) 这个作业的要求在哪里 作业要求 我在这个课程的目标是 积累软件开发经验,提高工程能力 这个作业在哪个具体方面帮助我实现目标 通读课 ...

  7. 安全高效跨平台的. NET 模板引擎 Fluid 使用文档

    Liquid 是一门开源的模板语言,由 Shopify 创造并用 Ruby 实现.它是 Shopify 主题的主要构成部分,并且被用于加载店铺系统的动态内容.它是一种安全的模板语言,对于非程序员的受众 ...

  8. 【ElasticSearch】ES 读数据,写数据与搜索数据的过程

    ES读数据的过程: 1.ES客户端选择一个node发送请求,该请求作为协调节点(coordinating node): 2.corrdinating node 对 doc id 对哈希,找出该文档对应 ...

  9. VPS、云主机 and 服务器集群、云计算 的区别

    VPS:(virtual private server)虚拟专用服务器,将一台服务器分割成多个虚拟专享服务器的优质服务.实现VPS的技术分为容器技术和虚拟化技术.在容器或虚拟机中,每个VPS都可分配独 ...

  10. hdu3117 斐波那契前后4位

    题意:       求斐波那契的前后4位,n <= 10^8. 思路:       至于前四位,和hdu1568的求法一样:       http://blog.csdn.net/u013761 ...