python类的高级函数

 

类的高级函数

__str__

如果定义了该函数,当print当前实例化对象的时候,会返回该函数的return信息

用法:

def __str__(self):

        return str_type

参数:无

返回值:一般返回对于该类的描述信息

__getattr__

当调用的属性或者方法不存在时,会返回该方法定义的信息

用法:

def __getattr__(self, key):

        print(something...)

参数:

    key:调用任意不存在的属性名

返回值:可以是任意类型也可以不进行返回

# coding: utf-8

class Test(object):
    def __str__(self):
        return 'this is a test class'

    def __getattr__(self, item):
        return '这个key:{}并不存在'.format(item)

t = Test()
print(t)
print(t.a)
print(t.b)

__setattr__

拦截当前类中不存在的属性与值

用法:

def __setattr__(self, key, value):

        self.__dict__[key] = value

参数:key当前的属性名,value当前的参数对应的值

返回值:无

__call__

本质是将一个类变成一个函数

用法:

def __call__(self, *args, **kwargs):

        print('call will start')

参数:可传任意参数

返回值:与函数情况相同可有可无

# coding: utf-8

class Test(object):
    def __str__(self):
        return 'this is a test class'

    def __getattr__(self, item):
        return '这个key:{}并不存在'.format(item)

    def __setattr__(self, key, value):
        self.__dict__[key] = value
        print(self.__dict__)

    def __call__(self, a):
        print('call func will start')
        print(a)

t = Test()
print(t)
print(t.a)
print(t.b)
t.name = 'xiaomu'
print(t.name)
t('dewei')

result:
this is a test class
这个key:a并不存在
这个key:b并不存在
{'name': 'xiaomu'}
xiaomu
call func will start
dewei

综合使用:

# t.a.b.c 链式操作
class Test2(object):
    def __init__(self, attr=''):
        self.__attr = attr

    def __call__(self, name):
        return name

    def __getattr__(self, key):
        if self.__attr:
            key = '{}.{}'.format(self.__attr, key)
        else:
            key = key
        print(key)
        return Test2(key)

t2 = Test2()
name = t2.a.b.c('dewei')
print(name)

result = t2.name.age.sex('ok')
print(result)
a
a.b
a.b.c
dewei
name
name.age
name.age.sex
ok

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Win_77

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值