Python中的魔法方法(也称为特殊方法或内置方法)是一系列以双下划线__
开头和结尾的方法。这些方法在特定操作或内置操作时被自动调用,例如__init__()
在对象创建时初始化对象,__len__()
返回容器的长度,__str__()
定义对象的字符串表示等。魔法方法允许开发者控制类的行为,使其与Python的数据类型和内置函数无缝协作,增强了类的功能性和灵活性。
python的魔法方法是通过__xx__()
下划线来进行调用,是python已经有的方法,可以直接使用
分类 | 方法 | 说明 | 作用 |
---|---|---|---|
算术运算符 | __add__(self, other) |
定义加法的行为:+ | |
算术运算符 | __sub__(self, other) |
定义减法的行为:- | |
算术运算符 | __mul__(self, other) |
定义乘法的行为:* | |
算术运算符 | __truediv__(self, other) |
定义真除法的行为:/ | |
算术运算符 | __floordiv__(self, other) |
定义整数除法的行为:// | |
算术运算符 | __mod__(self, other) |
定义取模算法的行为:百分号 | |
比较运算符 | __lt__(self, other) |
定义小于号的行为:x < y 调用 x.lt(y) | |
比较运算符 | __le__(self, other) |
定义小于等于号的行为:x <= y 调用 x.le(y) | |
比较运算符 | __eq__(self, other) |
定义等于号的行为:x == y 调用 x.eq(y) | |
比较运算符 | __ne__(self, other) |
定义不等号的行为:x != y 调用 x.ne(y) | |
比较运算符 | __gt__(self, other) |
定义大于号的行为:x > y 调用 x.gt(y) | |
比较运算符 | __ge__(self, other) |
定义大于等于号的行为:x >= y 调用 x.ge(y) | |
__doc__() |
文档解释 | ||
__sizeof__() |
打印系统分配空间的大小 | ||
__class__() |
调用子类方法 |
__doc__()
类解释
class ClassName:
'''
这个是我定义的类的注释
'''
def __init__(self):
'''
这是一个类属性
'''
index = ClassName()
print(index.__doc__) # print(index.__doc__)
print(index.__init__.__doc__) # 这是一个类属性
__sizeof__()
打印系统分配空间的大小
class Dog():
def d(self):
print("aa")
if __name__ == "__main__":
my_dog = Dog()
print(my_dog.__sizeof__())
__add__(self, other)
、__sub__(self, other)
、__truediv__(self, other)
、__floordiv__(self, other)
、__mod__(self, other)
class Dog:
def __init__(self):
self.x = 30
self.y = 8
main = Dog()
print(main.x.__add__(6)) # 定义减法的行为:+ 36
print(main.x.__sub__(6)) # 定义减法的行为:- 24
print(main.x.__mul__(6)) # 定义乘法的行为:* 180
print(main.x.__truediv__(6)) # 定义真除法的行为:/ 5.0
print(main.x.__floordiv__(6)) # 定义整数除法的行为:// 5
print(main.y.__mod__(6)) # 定义取模算法的行为:百分号 2
__gt__()
、__ge__()
、__le__()
、__lt__()
、__eq__()
、__ne__()
Python3中已经不能使用cmp()函数
import operator #首先要导入运算符模块
operator.gt(1,2) #意思是greater than(大于)
operator.ge(1,2) #意思是greater and equal(大于等于)
operator.eq(1,2) #意思是equal(等于)
operator.le(1,2) #意思是less and equal(小于等于)
operator.lt(1,2) #意思是less than(小于)
operator.__lt__(a, b)
operator.__le__(a, b)
operator.__eq__(a, b)
operator.__ne__(a, b)
operator.__ge__(a, b)
operator.__gt__(a, b)
lt(a, b) 相当于 a < b
le(a,b) 相当于 a <= b
eq(a,b) 相当于 a == b
ne(a,b) 相当于 a != b
gt(a,b) 相当于 a > b
ge(a, b)相当于 a>= b
__class__()
调用子类
class Foo(object):
def create_new(self):
return self.__class__()
def create_new2(self):
return Foo()
class Bar(Foo):
pass
b = Bar()
c = b.create_new()
print type(c) # We got an instance of Bar
d = b.create_new2()
print type(d) # we got an instance of Foo