専門ユニット2/山内研セミナー(2021/10/26)

関連サイトと資料

補足

前回最後のMyStackクラス
class MyStack:
    def __init__(self, *args):
        self.stack = []
        for item in args:
            self.stack.append(item)
    def push(self, item):
        self.stack.append(item)
    def pop(self):
        if len(self.stack) == 0:
            return None
        return self.stack.pop()
    def __repr__(self):
        return 'MyStack(' + repr(self.stack) + ')'
    def __str__(self):
        return str(self.stack)
    def __iter__(self):
        return reversed(self.stack)
    def __getitem__(self, key):
        return self.stack[key]
    

__setitem__の追加

class MyStack:
    def __init__(self, *args):
        self.stack = []
        for item in args:
            self.stack.append(item)
    def push(self, item):
        self.stack.append(item)
    def pop(self):
        if len(self.stack) == 0:
            return None
        return self.stack.pop()
    def __repr__(self):
        return 'MyStack(' + repr(self.stack) + ')'
    def __str__(self):
        return str(self.stack)
    def __iter__(self):
        return reversed(self.stack)
    def __getitem__(self, key):
        return self.stack[key]
    def __setitem__(self, key, value):
        self.stack[key] = value
    

mystack = MyStack(1, 2, [3, 4])
mystack[0] = -1
print(mystack[0])
mystack[0:2] = [10, 20]
print(mystack)
    

__delitem__の追加

class MyStack:
    def __init__(self, *args):
        self.stack = []
        for item in args:
            self.stack.append(item)
    def push(self, item):
        self.stack.append(item)
    def pop(self):
        if len(self.stack) == 0:
            return None
        return self.stack.pop()
    def __repr__(self):
        return 'MyStack(' + repr(self.stack) + ')'
    def __str__(self):
        return str(self.stack)
    def __iter__(self):
        return reversed(self.stack)
    def __getitem__(self, key):
        return self.stack[key]
    def __setitem__(self, key, value):
        self.stack[key] = value
    def __delitem__(self, key):
        del self.stack[key]
    

mystack = MyStack(1, 2, [3, 4])
del mystack[0:2]
print(mystack)
    

__len__の追加

class MyStack:
    def __init__(self, *args):
        self.stack = []
        for item in args:
            self.stack.append(item)
    def push(self, item):
        self.stack.append(item)
    def pop(self):
        if len(self.stack) == 0:
            return None
        return self.stack.pop()
    def __repr__(self):
        return 'MyStack(' + repr(self.stack) + ')'
    def __str__(self):
        return str(self.stack)
    def __iter__(self):
        return reversed(self.stack)
    def __getitem__(self, key):
        return self.stack[key]
    def __setitem__(self, key, value):
        self.stack[key] = value
    def __delitem__(self, key):
        del self.stack[key]
    def __len__(self):
        return len(self.stack)
    

mystack = MyStack(1, 2, [3, 4])
print(len(mystack))