常见的魔法方法及使用

常见的魔法方法有如下:

__init__   初始化类属性的方法
__repr__   定义 当 repr()  被你的一个类的实例调用时所要产生的行为。 str() 和 repr() 的主要区别是其目标群体。 repr() 返回的是机器可读的输出,而 str() 返回的是人类可读的。
__str__    定义当 str() 被你的一个类的实例调用时所要产生的行为。后面例子中print输出的时候就相当于在调用方法__str____call__   使一个类的实例像函数一样被调用:x(a, b) 调用 x.__call__(a, b), c1()   使实例可被调用

__init__方法示例代码:

 1 class Rectangle:
 2     def __init__(self,width,height):
 3         self.width = width
 4         self.height = height
 5
 6
 7 C1=Rectangle(3,4)
 8
 9 #输出结果:
10 >>> C1.width
11 3
12 >>> C1.height
13 4
14 >>> 

__repr__方法示例代码:

 1 class Rectangle:
 2      def __init__(self,width,height):
 3          self.width = width
 4          self.height = height
 5
 6
 7      def __str__(self):
 8
 9          return ‘宽度为%s,高度为%s‘%(self.width,self.height)
10
11
12      def __repr__(self):
13
14          return ‘面积为%s‘ % self.area()
15
16      def area(self):
17
18          return self.width*self.height
19
20  C1=Rectangle(3,4)
21
22  #输出结果:
23  >>> C1
24 面积为12
25  >>> C1.area()
26  12
27  >>> C1.__repr__
28  <bound method Rectangle.__repr__ of 面积为12>
29  >>> C1.__repr__()
30  ‘面积为12‘
31  >>> 

__str__方法示例代码:

 1 class Rectangle:
 2     def __init__(self,width,height):
 3         self.width = width
 4         self.height = height
 5
 6
 7 C1=Rectangle(3,4)
 8
 9 #输出结果:
10 >>> C1
11 <__main__.Rectangle object at 0x0000000002B38550>
12 >>> print(C1)
13 <__main__.Rectangle object at 0x0000000002B38550>
14
15 >>>
16 >>> C1.__str__
17 <method-wrapper ‘__str__‘ of Rectangle object at 0x0000000002B38550>
18 >>> C1.__str__()
19 ‘<__main__.Rectangle object at 0x0000000002B38550>‘
20 >>>
21
22 #改写__str__方法后
23 class Rectangle:
24     def __init__(self,width,height):
25         self.width = width
26         self.height = height
27
28     def __str__(self):
29
30         return ‘宽度为%s,高度为%s‘%(self.width,self.height)
31
32 C1=Rectangle(3,4)
33
34 #输出结果:
35 >>> C1
36 <__main__.Rectangle object at 0x0000000002B384E0>
37 >>> C1.width
38 3
39 >>> C1.height
40 4
41 >>> print(C1)
42 宽度为3,高度为4
43 >>> 

改写__str__方法后让返回值以为指定的模式输出,这里用 return ‘宽度为%s,高度为%s‘%(self.width,self.height)返回一个字符串形式

__call__方法代码:

 1 class Rectangle:
 2     def __init__(self,width,height):
 3         self.width = width
 4         self.height = height
 5
 6
 7     def __str__(self):
 8
 9         return ‘宽度为%s,高度为%s‘%(self.width,self.height)
10
11
12     def __repr__(self):
13
14         return ‘面积为%s‘ % self.area()
15
16     def area(self):
17
18         return self.width*self.height
19
20 C1=Rectangle(3,4)
21
22 #输出结果:
23 >>> C1
24 面积为12
25 >>> C1()
26 Traceback (most recent call last):
27   File "<pyshell#92>", line 1, in <module>
28     C1()
29 TypeError: ‘Rectangle‘ object is not callable
30 >>> 

改写__call__方法

 1 class Rectangle:
 2     def __init__(self,width,height):
 3         self.width = width
 4         self.height = height
 5
 6
 7     def __str__(self):
 8
 9         return ‘宽度为%s,高度为%s‘%(self.width,self.height)
10
11
12     def __repr__(self):
13
14         return ‘面积为%s‘ % self.area()
15
16     def __call__(self):
17
18         return ‘测试这个类是否可调用‘
19
20     def area(self):
21
22         return self.width*self.height
23
24 C1=Rectangle(3,4)
25
26 #输出结果:
27 >>> C1
28 面积为12
29 >>> C1()
30 ‘测试这个类是否可调用‘
31 >>> 

__add__方法代码示例:

 1 class Rectangle:
 2     def __init__(self,width,height):
 3         self.width = width
 4         self.height = height
 5     def __str__(self):
 6         return ‘宽为%s,高为%s‘ % (self.width,self.height)
 7     def __repr__(self):
 8         return ‘面积为%s‘ % self.area()
 9     def __call__(self):
10         return ‘hahahha‘
11     def area(self):
12         return self.width*self.height
13     def __add__(self,other):
14         if isinstance(other,Rectangle):
15             return self.area()+other.area()
16
17 C1=Rectangle(3,4)
18 C2=Rectangle(5,6)
19 #输出结果:
20 >>> C1
21 面积为12
22 >>> C2
23 面积为30
24 >>> C1 + C2
25 42
26 >>> 

其他常见的运算符魔法方法:

 1 __add__(self,other)     x+y
 2 __sub__(self,other)     x-y
 3 __mul__(self,other)     x*y
 4 __mod__(self,other)    x%y
 5 __iadd__(self,other)    x+=y
 6 __isub__(self,other)    x-=y
 7 __radd__(self,other)    y+x
 8 __rsub__(self,other)     y-x
 9 __imul__(self,other)    x*=y
10 __imod__(self,other)    x%=y
时间: 2024-07-31 15:03:25

常见的魔法方法及使用的相关文章

Python基础教程(第九章 魔法方法、属性和迭代器)

本文内容全部出自<Python基础教程>第二版,在此分享自己的学习之路. ______欢迎转载:http://www.cnblogs.com/Marlowes/p/5437223.html______ Created on Marlowes 在Python中,有的名称会在前面和后面都加上两个下划线,这种写法很特别.前面几章中已经出现过一些这样的名称(如__future__),这种拼写表示名字有特殊含义,所以绝不要在自己的程序中使用这样的名字.在Python中,由这些名字组成的集合所包含的方法称

python 魔法方法(学习过程的笔记)

有小伙伴会问,什么是python的魔法方法,python的魔法方法有什么用呢, 它们在面向对象的Python的处处皆是.它们是一些可以让你对类添加"魔法"的特殊方法. 它们经常是两个下划线包围来命名的. 我感觉魔法方法很牛逼的, 目前我们常见的魔法方法大致可分为以下几类: 构造与初始化 类的表示 访问控制 比较操作 容器类操作 可调用对象 Pickling序列化 在我们写python中最常见的就是__init__,这是python的构造方法,这是初始化对象,定义一个对象的初始化的值,_

python魔法方法-属性访问控制

属性访问控制 所谓的属性访问控制就是控制点号访问属性的行为,而且不仅是类的外部,连类的内部也受控制,代码见真章,边看代码边解释: __getattr__(self, item) 定义当访问不存在的属性时的行为,注意是不存在的属性. class Foo(object): def __init__(self, value): self.value = value def __getattr__(self, item): print item # 查看得到的参数是什么 print type(item)

魔法方法之自定义序列

自定义序列 自定义序列的相关魔法方法允许我们自己创建的类拥有序列的特性,让其使用起来就像 python 的内置序列(dict,tuple,list,string等). 因为如果要定制容器类型的话需要用到这些协议.首先,实现不变容器的话有一个协议:实现不可变容器,你只能定义__len__ 和 __getitem__ (一会会讲更多).可变容器协议则需要所有不可变容器的所有另外还需要 __setitem__ 和 __delitem__ .最终,如果你希望你的对象是可迭代的话,你需要定义 __iter

python_面向对象魔法方法指南

原文: http://www.rafekettler.com/magicmethods.html 原作者: Rafe Kettler 翻译: hit9 原版(英文版) Repo: https://github.com/RafeKettler/magicmethods Contents (译)Python魔法方法指南 简介 构造方法 操作符 比较操作符 数值操作符 一元操作符 常见算数操作符 反射算数运算符 增强赋值运算符 类型转换操作符 类的表示 访问控制 自定义序列 预备知识 容器背后的魔法方

3.5 魔法方法

目录 3.5.1 python3 变动 3.5.2 构造方法 3.5.3 可调用的对象 3.5.4 类的访问控制 3.5.5 类的表示 3.5.6 容器背后的魔法方法 3.5.7 操作符 3.5.7.1比较操作符 3.5.7.2 常见数值操作符 3.5.7.3 反射算数运算符 3.5.7.4 增强赋值运算符 3.5.7.5 类型转换操作符 3.5.8 上下文管理 3.5.9 反射 3.5.10 创建描述符对象 3.5.11 拷贝 3.5.1 python3 变动 3.5.2 构造方法 3.5.3

&lt;&lt;Python基础教程&gt;&gt;学习笔记 | 第09章 | 魔法方法、属性和迭代器

这一章,有点抽象,看着有点蛋疼! 双下划线__future__或单下划线有特殊含义,在Python中,这些名字的集合称为魔法方法:最重要的是__init__和一些处理访问对象的方法,这些方法允许你创建自己的序列或者是映射. ------ 准备工作: 将__metaclass__=type放在模块的最开始位置,以确保类时最新式的.考虑下面两个类 class NewStyle(object): more_code_here class OldStyle: more_code_here 如果文件以__

evo加速器常见错误代码解决方法

evo加速器常见错误代码解决方法  --------------------------------------------------------------------------------------------------------------         691                账号没有通过验证.解决方法1.检查账号密码是否输入错误,是否可以正常登陆我们的官网.2.免费(付费)用户进入用户中心检查自己的免费(付费)时间或流量是否用完或到期. -----------

python魔法方法详解

文章来源:http://blog.csdn.net/koko66/article/details/42709279 据说,Python 的对象天生拥有一些神奇的方法,它们总被双下划线所包围,他们是面向对象的 Python 的一切. 他们是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了这些方法中的某一个,那么这个方法就会在特殊的情况下被 Python 所调用,你可以定义自己想要的行为,而这一切都是自动发生的. Python 的魔术方法非常强大,然而随之而来的则是责任.了解正确的方法去使