python之有关魔方方法的内容

魔方方法:

在python的类中,以下划线开头,两个下划线结尾的方法,如常见的:init,str,__del__等,就被称为魔方方法,这些方法在类或对象进行特定的操作时会被自动调用,我们可以使用或重写这些魔方方法,给自定义的类添加各种特殊的功能来满足自己的需求。

常见的魔方方法:

init:

init()方法是我们最常见的魔方方法,可以用此方法定义一个对象的初始化操作。
例如:

class Car:
def __init__(self,Color,WheelNum):
        self.color = Color#初始化操作,不设定值
        self.wheelNum = WheelNum

new:

init()方法很容易被认为是在实例化对象时,调用的第一个方法,但其实不是,当我们实例化一个对象的时候,第一个被调用的方法是__new__(),而后再调用__init__()方法,并把一些参数传给__init__()方法,new()方法才是真正创建了实例化对象,init()方法只是给这个对象进行了初始化操作。
举例:

class Car:
    def __init__(self,color,wheelnum):
        print("__init__()方法被调用")
        self.color=color
        self.wheelnum=wheelnum
         print(id((self)))
    def __new__(cls, *args, **kwargs):#接收任意数量的位置实参和关键字实参
        print("__new__()方法被调用")
        print("args:",args)
        c=super().__new__(cls)#cls表示当前类
        print(id(c))
        return c#有返回,调用__init__函数
my_car=Car("蓝色",8)
__new__()方法被调用#new函数先被调用
args: ('蓝色', 8)
1955709945024
__init__()方法被调用
1955709945024

new()方法第一个参数必须是cls参数,表示当前类,其他参数是用来直接传递给__init__方法,__new__决定是否要使用该__init__方法,因为__new__可以调用其他类的构造方法或直接返回别的实例对象来作为本类的实例,如果__new__没有返回实例对象,则__init__不会被调用,__new__主要是用于继承一个不可变的类型,例如:元组或者字符串

del:

当一个对象的生命周期结束被彻底销毁的时候被调用,编译器会默认调用__del__方法.

class Car:
    def __init__(self,color,wheelnum):
        print("__init__()方法被调用")
        self.color=color
        self.wheelnum=wheelnum
    def __del__(self):
        print("__del__()方法被调用")#被调用后,该变量所占用的内存块被释放
my_car=Car("蓝色",8)
print(my_car.color)

__new__和__init__的id值相同,它两相配合才是python中真正的类构造器

__init__()方法被调用
蓝色
__del__()方法被调用

str:

如果要把一个类的实例变成str,就需要实现特殊方法__str__()

举例:

class Car:
    def __init__(self,color,wheelnum):
        print("__init__()方法被调用")
        self.color=color
        self.wheelnum=wheelnum
    def __str__(self):#将实例转化为字符串
        return (f"我的汽车颜色是{self.color},它有{self.wheelnum}个轮子")
my_car=Car("蓝色",8)
print(my_car)
__init__()方法被调用
我的汽车颜色是蓝色,它有8个轮子

setattr函数和getattr函数

setattr()函数用于设置属性,该属性不一定存在。

def __setattr__(object,key,value):#object---对象,key----字符串,对象属性,value----属性值

举例:

class Car:
    def __init__(self,color,wheelnum):
        print("__init__()方法被调用")
        self.color="红色"
        self.wheelnum=8
my_car=Car("蓝色",8)
print("设置属性前:")
print(my_car.color)
print(my_car.wheelnum)
setattr(my_car,"color","白色")#设置对象属性的值
setattr(my_car,"wheelnum",10)#设置对象属性的值
print("设置属性后:")
print(my_car.color)
print(my_car.wheelnum)
__init__()方法被调用
设置属性前:
红色
8
设置属性后:
白色
10

gatattr()函数用于获取属性。

def __getattr__(object,key)#object-----对象,key-----对象属性

举例:

class Car:
    def __init__(self,color,wheelnum):
        print("__init__()方法被调用")
        self.color="红色"
        self.wheelnum=8
my_car=Car("蓝色",8)
print(getattr(my_car,"color"))#输出对象对应属性的值
__init__()方法被调用
红色

类型转换相关魔方方法:

class Car:
    def __init__(self,color,wheelnum):
        print("__init__()方法被调用")
        self.color="红色"
        self.wheelnum=8
    def __int__(self):#将对应的属性wheelnum的值转化为int类型的结果并返回给__init__()函数
        return self.wheelnum
    def __float__(self):#将对应的属性wheelnum的值转化为float类型的结果并返回给__init__()函数
        return self.wheelnum*1.0
    def __str__(self):#将对应的属性color的值转化为str类型的结果并返回给__init__()函数
        return self.color
    def __bool__(self):#将对应的属性wheelnum判断的结果转化为bool类型的结果并返回给__init__()函数
        return self.wheelnum>5
my_car=Car("蓝色",8)
#强制类型转换
print(int(my_car))
print(float(my_car))
print(str(my_car))
print(bool(my_car))
__init__()方法被调用
8
8.0
红色
True

算数运算符相关的魔方方法:

class Student:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __add__(self, other):#进行self.age+other的运算
    #并将self.age+实参的结果返回给__init__()函数
        return self.age+other
    def __sub__(self, other):
        return self.age-other
    def __mul__(self, other):
        return self.age*other
    def __truediv__(self, other):
        return self.age/other
    def __mod__(self, other):
        return self.age%other
    def __pow__(self, power, modulo=None):#平方和运算
        return self.age**power
s=Student("易烊千玺",22)
#算数运算
print(s+1)
print(s-2)
print(s*3)
print(s/4)
print(s%5)
print(s**6)
23
20
66
5.5
2
113379904

比较运算符相关的魔方方法:

class Student:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __eq__(self, other):#比较对象的各个属性值是否都相等
        return self.name==other.name and self.age==other.age
    def __lt__(self, other):#比较对象的某一属性之间的大小关系
        return self.age<other.age
    def __le__(self, other):#比较对象的某一属性之间的大小关系
        return self.age<=other.age
student1=Student("易烊千玺",22)
student2=Student("王源",22)
student3=Student("王俊凯",23)
print(student1==student2)
print(student1!=student3)
print(student2==student3)
print(student1>=student2)
print(student1>=student3)
print(student2<=student3)
#比较运算符返回结果均为布尔值(False、True)
False
True
False
True
False
True
  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

从未止步..

谢谢你的打赏,我会继续努力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值