python面向对象中__xx__函数

在学习面向对象时,我们在定义一个类时会用几个常用的函数,可以看作是内置函数

1.__init__

作用:初始化对象

不带参数的init

class House():

    def __init__(self):

        self.length = 400

        self.height = 300

    def print_info(self):

        print(f'{self.length} {self.height}')

BigHouse = House()

BigHouse.print_info()

带参数的init

class House():

    def __init__(self,length,height):

        self.length = length

        self.height = height

    def print_info(self):

        print(f'{self.length} {self.height}')

BigHouse = House(400,300)

BigHouse.print_info()

像是定义函数时的形参

2.__str__

作用:当print对象时默认输出对象的 内存地址,使用此函数可以打印出return的数据

class House():

    def __init__(self,length,height):

        self.length = length

        self.height = height

    def __str__(self):

        return '你开心就好'

BigHouse = House(400,300)

print(BigHouse)

3.__del__

当删除对象时,解释器默认调用del函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值