Discuss / Python / 不是很了解链式调用的作用 不过先写了再说

不是很了解链式调用的作用 不过先写了再说

Topic source

留白A_Z

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-
# @Author: adolph
# @Date:   2020-08-01 13:00:37
# @Last Modified by:   adolph
# @Last Modified time: 2020-08-01 15:27:59


class Chain():
    def __init__(self, path=''):
        self.path = path

    def __getattr__(self, path):    # 动态返回属性
        return Chain('%s/%s' % (self.path, path))

    def __str__(self):
        return self.path

    def __call__(self):    # 调用实例
        print('Final path is: %s' % self.path)
        return

    def users(self, name):
        return Chain('%s/:%s' % (self.path, name.lower()))


# test Chain
Chain().home.users('Adolph').profile()

""" 
__call__()没有显式的使用return语句
python 解释器会隐式地返回一个 return None
"""
print(Chain().home.users('Adolph').profile())

print(Chain().home.users('Adolph').profile)


  • 1

Reply