Jul-07-2023, 04:16 AM
I only use Python for practical purposes, to do little jobs. I never found a task where I thought I need a class.
Today I was just looking at a class, see below.
When I write R. in Idle, a little window appears with append, data head.
If I write R._ the little window contains a long list of things.
What is all that info?? What can I do with it?
Today I was just looking at a class, see below.
When I write R. in Idle, a little window appears with append, data head.
If I write R._ the little window contains a long list of things.
What is all that info?? What can I do with it?
class Rotating:
"""Rotate a list as new items are added. List stays the same length."""
def __init__(self, items):
self.data = list(items)
self.head = 0
def __iter__(self):
for i in range(len(self)):
yield self[i]
def __getitem__(self, i):
return self.data[(i + self.head) % len(self)]
def __len__(self):
return len(self.data)
def append(self, item):
self.data[self.head] = item
self.head = (self.head + 1) % len(self)
def __str__(self):
return 'Rotating({})'.format(
self.data[self.head:] + self.data[:self.head])
R = Rotating('abcdef')
print(R)
R.append('g')
print(R)
R.append('h')
print(R)
print(R[0], len(R), R[5])
print(R.data)
