Skip to content

Commit

Permalink
[优化]__getitem__
Browse files Browse the repository at this point in the history
  • Loading branch information
longfengpili committed Oct 31, 2023
1 parent 012bac3 commit 2baa450
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
18 changes: 9 additions & 9 deletions pydbapi/col/colmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# @Author: longfengpili
# @Date: 2023-06-02 15:27:41
# @Last Modified by: longfengpili
# @Last Modified time: 2023-10-31 10:25:06
# @Last Modified time: 2023-10-31 11:30:48
# @github: https://github.com/longfengpili

from typing import Iterable, List, Any
Expand Down Expand Up @@ -54,19 +54,19 @@ def __init__(self, *columns):
self.columns = list(columns)

def __repr__(self):
return f"{self.columns}"
return f"ColumnsModel({self.columns})"

def __getitem__(self, index: int):
if isinstance(index, slice):
start, stop, step = index.indices(len(self.columns))
return [self.columns[i] for i in range(start, stop, step)]
elif 0 <= index < len(self.columns):
return self.columns[index]
return ColumnsModel(*[self.columns[i] for i in range(start, stop, step)])
elif -len(self.columns) <= index < len(self.columns):
return ColumnsModel(self.columns[index])
else:
raise IndexError("Index out of range")

def __setitem__(self, index: int, column: ColumnModel):
if 0 <= index < len(self.columns):
if -len(self.columns) <= index < len(self.columns):
self.columns[index] = column
else:
raise IndexError("Index out of range")
Expand All @@ -80,9 +80,9 @@ def extend(self, iterable: Iterable[Any]) -> None:
def __len__(self) -> int:
return len(self.columns)

# def __iter__(self):
# for column in self.columns:
# yield column
def __iter__(self):
for column in self.columns:
yield column

def __contains__(self, name):
col = self.get_column_by_name(name)
Expand Down
6 changes: 4 additions & 2 deletions tests/colmodel/test_colmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# @Author: longfengpili
# @Date: 2023-06-02 15:27:41
# @Last Modified by: longfengpili
# @Last Modified time: 2023-10-31 10:26:10
# @Last Modified time: 2023-10-31 11:28:13
# @github: https://github.com/longfengpili


Expand All @@ -22,10 +22,12 @@ def setup_method(self, method):
def teardown_method(self, method):
pass

def test_column_getter(self):
def test_column_by_name(self):
colname = 'score'
col = self.columns.get_column_by_name(colname)
print(col)

def test_column_getter(self):
col = self.columns[0]
print(col)
cols = self.columns[1:3]
Expand Down

0 comments on commit 2baa450

Please sign in to comment.