我正在尝试创建一个包含一堆整数的类。我正在使用set
做同样的事情。但是我想通过以其他某种形式存储连续范围来压缩内存占用,这可能是一个范围对象。但是在这种情况下,我将如何实现union
,intersection
,issubset
等功能?
下面是我到目前为止的代码。在__init__
中,我想实现一个压缩功能,以使连续范围不会按原样存储。另外,我想接受范围作为项目的一部分。
class Component(object):
"""
Component class
Attributes:
name (str): The name of the component.
type (str): The type of the component.
items (set): The members of the component.
"""
def __init__(self, comp_name, comp_type, comp_items):
"""
Constructor for the Component object.
Args:
comp_name (str): Name of the component.
comp_type (str): Type of the component.
comp_items (iterable): An iterable of the members of the component.
"""
self.name = comp_name
self.type = comp_type.lower()
if not all(isinstance(x, int) for x in comp_items):
raise TypeError("All items in the component items should of type int")
self.items = set(comp_items)
@property
def count(self):
"""Return the number of items in the component"""
return len(self.items)
def max(self):
"""Returns the max ID number from the component items"""
return max(self.items)
def min(self):
"""Returns the min ID number from the component items"""
return min(self.items)
def __repr__(self):
"""Representation of the component"""
return "<Component Object-> Name:{}, Type:{}, Count: {}>".format(
self.name, self.type, self.count
)
def __len__(self):
"""len() function on the Component object"""
return len(self.items)
def __eq__(self, other):
"""Checking if one component is equal to another"""
return self.type == other.type and self.items == other.items
def __and__(self, other):
"""Intersection of two components"""
assert self.type == other.type
return self.__class__("", self.type, self.items & other.items)
def __or__(self, other):
"""Union of two components"""
assert self.type == other.type
return self.__class__("", self.type, self.items | other.items)
def __add__(self, other):
"""Adding two components together"""
return self.__or__(other)
def __sub__(self, other):
"""Removing one Component from another"""
assert self.type == other.type
return self.__class__("", self.type, self.items - other.items)
def issubset(self, other):
"""Checking if self is a subset of other"""
return self.items.issubset(other.items)
def __contains__(self, other):
return self.items.__contains__(other)