小尹学python

导航

Python:案例之getitem、__call__、

class StarkConfig(object):
    def __init__(self, num):
        self.num = num

    def run(self):
        self()

    def __call__(self, *args, **kwargs):
        print(self.num)


class RoleConfig(StarkConfig):
    def __call__(self, *args, **kwargs):
        print(345)

    def __getitem__(self, item):
        return self.num[item]


v1 = RoleConfig('alex')
v2 = StarkConfig("wupeiqi")

print(v1[1])  # v1[1],会去找getitem,将1传给item
# print(v2[2])  没有getitem,报错

class Node(object):
    def __init__(self, title):
        self.title = title
        self.children = []

    def add(self, node):
        self.children.append(node)

    def __getitem__(self, item):
        return self.children[item]


root = Node("中国")

root.add(Node("河南省"))
root.add(Node("河北省"))

print(root.title)
print(root[0])
print(root[0].title)
print(root[1])
print(root[1].title)

class Node(object):
    def __init__(self, title):
        self.title = title
        self.children = []

    def add(self, node):
        self.children.append(node)

    def __getitem__(self, item):
        return self.children[item]


root = Node("中国")  # title=中国,children = []

root.add(Node("河南省"))  # Node对象,title=河南省,children = []
root.add(Node("河北省"))  # Node对象,title=河北省,children = []
root.add(Node("陕西省"))  # Node对象,title=陕西省,children = []
root.add(Node("山东省"))  # Node对象,title=山东省,children = []
# 此时,root里的children= [Node对象(title=河南省,children = []),Node对象(title=河北省,children = []),Node对象(title=陕西省,children = []),Node对象(title=山东省,children = [])]

root[1].add(Node("石家庄"))
root[1].add(Node("保定"))
root[1].add(Node("廊坊"))
# root[1],执行__getitem__,item=1,因此提取的是”Node对象(title=河北省,children = [])“
# 执行后,root[1]里的children列表内容为[Node对象(title=石家庄,children = []),Node对象(title=保定,children = []),Node对象(title=廊坊,children = [])]

root[3].add(Node("潍坊"))
root[3].add(Node("烟台"))
root[3].add(Node("威海"))
# root[3],执行__getitem__,item=3,因此提取的是”Node对象(title=山东省,children = [])“
# 执行后,root[3]里的children列表内容为[Node对象(title=潍坊,children = []),Node对象(title=烟台,children = []),Node对象(title=威海,children = [])]

root[1][1].add(Node("雄安"))
root[1][1].add(Node("望都"))
# root[1][1],执行__getitem__,item=1,因此提取的是”Node对象(title=保定,children = [])“
# 执行后,root[1][1]里的children列表内容为[Node对象(title=雄安,children = []),Node对象(title=望都,children = [])]


print(root.title)  # 中国
print(root[0].title)  # 河南省
print(root[1].title)  # 河北省
print(root[1][0].title)  # 石家庄
print(root[1][2].title)  # 廊坊
print(root[1][1][0].title)  # 雄安

posted on 2021-11-14 14:44  小尹学python  阅读(130)  评论(0)    收藏  举报