Python类与魔法方法

__xx__()的函数叫做魔法方法,指的是具有特殊功能的函数

 

1.__init__()

作用:用于初始化对象

class Washer():
    
    def __init__(self):
        self.width = 500
        self.height = 800

    def print_info(self):
        print(f'洗衣机的宽度是{self.width}, 高度是{self.height}')

haier1 = Washer()
haier1.print_info()

运行结果:

洗衣机的宽度是500, 高度是800

需要我们传递参数时:

class Washer():
    
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def print_info(self):
        print(f'洗衣机的宽度是{self.width}, 高度是{self.height}')

haier1 = Washer(10, 20) 
haier1.print_info(
)
haier2 = Washer(20, 30)
haier2.print_info()

运行结果:

洗衣机的宽度是10, 高度是20

洗衣机的宽度是20, 高度是30

 

 

2.__str__()

使用print输出一个对象时,默认打印对象的内存地址,定义了__str__方法后,打印出来的就是__str__方法返回的数值。

class Washer():

    def __init__(self,width,height):
        self.width = width
        self.height = height

    def __str__(self):
        return 'This one is for washing'
    def print_info(self):
        print(f'洗衣机的宽度是{self.width}, 高度是{self.height}')


haier1 = Washer(10, 20)
print(haier1)

运行的结果:

This one is for washing

 

 

3.__del__()

是一个当对象被删除时,python解释器默认调用的方法

def __del__(self):
    print(f'object has been deleted')

 

posted @ 2020-06-10 22:37  鸡龟骨滚羹  阅读(119)  评论(0)    收藏  举报