如何将一些内置方法转移到类变量?

问题描述 投票:0回答:1

我有一个类,我希望通过类变量实现类似列表或类似dict的行为。

class Property(list):
    def __init__(self, data: list = None, name: str):
        self.data = data or []
        self.name = name

prop = Property([1,2,3,4,5,6,7,8,9,10], 'property')
print(prop[1])  # 2
print(prop[:3])  # [1, 2, 3]
print(prop.name)  # 'property'

我希望Property在使用一些列表方法调用时,比如append(),pop(),index()以使用self.data变量作为列表。

class Node(dict):
    def __init__(self, data: dict = None):
        self.data = data or {}
        self.order = []
        for x in data:
            # do stuff to fill data & order

node = Node({'a': '1', 'b': '2', 'c': '3'})
print(node.keys())  # ['a', 'b', 'c']
print('c' in node)  # True
print(node['b'])  # '2'
print(node.order)  # some ordered list

同样在这里,我希望它直接使用类似dict的方法的self.data变量。

有没有办法像super().__init__()这样做?

python python-3.x class inheritance
1个回答
0
投票

您需要collections模块中的UserList和UserDict类。您无法通过直接从内置列表和dict类型继承来获得您期望的行为,因为它们是在C中实现的(至少在CPython中),因此这些类是为此目的而创建的。

from collections import UserList, UserDict, OrderedDict

class Property(UserList):
    def __init__(self, data: list = None, name: str = None):
        self.data = data or []
        self.name = name

prop = Property([1,2,3,4,5,6,7,8,9,10], 'property')
print(prop[1])  # 2
print(prop[:3])  # [1, 2, 3]
print(prop.name)  # 'property'

class Node(UserDict):
    def __init__(self, data: dict = None):
        self.data = OrderedDict(data) if data else OrderedDict()

node = Node({'a': '1', 'b': '2', 'c': '3'})
print(node.keys())  # KeysView(OrderedDict([('a', '1'), ('b', '2'), ('c', '3')]))
print([c for c in node.keys()]) # ['a','b','c']
print('c' in node)  # True
print(node['b'])  # '2'

你需要在你的dict课上做更多的工作,但我想你可以搞清楚。

值得注意的是,您可以将OrderedDict用于节点数据,从而为您提供所需的订单。

© www.soinside.com 2019 - 2024. All rights reserved.