魔法方法——Python

  • 特征即是属性
  • 行为即是方法
  • self表示调用该函数的对象

魔法方法
在Python中, __ xx_()的函数叫做魔法方法,指的是具有特殊功能的函数。
_init():初始化对象

class Washer():
    def __init__(self):
        #添加实例属性
        self.width=500
        self.height=800
    def print_info(self):
        print(f'洗衣机的宽度是{self.width},高度是{self.height}')

haier=Washer()
haier.print_info()
输出:
洗衣机的宽度是500,高度是800
#init()方法:在创建一个对象时默认被调用,不需要手动调用
#init(self)中的self参数,不需要开发者传递,Python解释器会自动把当前的对象引用传递过去

带参数的init方法

class Washer():
    def __init__(self,width,height):
        #添加实例属性
        self.width=width
        self.height=height
    def print_info(self):
        print(f'洗衣机的宽度是{self.width},高度是{self.height}')

haier=Washer(10,20)
haier.print_info()
输出:
洗衣机的宽度是10,高度是20

__ str __()
当使用print输出对象的时候,默认打印对象的内存地址。如果类定义了str()方法,那么就会打印从在这个方法中return的数据

class Washer():
    def __init__(self,width,height):
        #添加实例属性
        self.width=width
        self.height=height
    def print_info(self):
        print(f'洗衣机的宽度是{self.width},高度是{self.height}')
    def __str__(self):
        return '这是海尔洗衣机的说明书'

haier=Washer(10,20)
print(haier)
输出:
这是海尔洗衣机的说明书

del方法
当删除对象时,Python解释器会默认调用del()方法

class Washer():
    def __init__(self,width,height):
        #添加实例属性
        self.width=width
        self.height=height
    def print_info(self):
        print(f'洗衣机的宽度是{self.width},高度是{self.height}',end='\n')
    def __str__(self):
        return '这是海尔洗衣机的说明书'
    def __del__(self):
        print(f'{self}对象已被删除')

haier=Washer(10,20)

del haier
输出:
这是海尔洗衣机的说明书对象已被删除
发布了61 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43717681/article/details/104121701