from abc import ABC, abstractmethod from debug_log import p class AbstractService(ABC): # abstractmethodには引数がない @abstractmethod def test(self) -> int: pass class ImplService(AbstractService): # 具象methodには引数がある def test(self, a: int, b: int) -> int: return a + b def print_method(service: AbstractService) -> int: return service.test(a=1, b=2) service = ImplService() test_value = print_method(service=service) p(test_value)
- https://docs.python.org/ja/3/reference/datamodel.html#object.__hash__ """ class Item: def __init__(self, value: int): self.value = value item_1 = Item(1) item_2 = Item(1) # valueが同じでも違うオブジェクトとして判定される(これは当たり前) is_same_item = item_1 == item_2 p(is_same_item) # False item_set = {item_1} p(item_set) # 同じオブジェクトは追加できない item_set.add(item_1) p(item_set) # 違うオブジェクトなので追加できる item_set.add(item_2) p(item_set)
from dataclasses import dataclass from enum import Enum, auto from debug_log import p # dataclassとenumは共存できない?どちらにせよ複雑になりそうだからあまりよくなさそうだが @dataclass class EnumLike(Enum): EMPTY = auto() val: int = 0 # instance = EnumLike(1) enum_like_value = EnumLike.EMPTY # p(instance) p(enum_like_value)
from __future__ import annotations # python3.9時点だと、このimportしないと -> Testの部分で落ちる from debug_log import p class Test: def __init__(self, value: str): self.value = value def from_str(self, value: str) -> Test: return Test(value + '!!!!!!!!!!!!!!!!1') test = Test('value') p(test.from_str('this is test'))
from debug_log import p l1 = [1, 2, 3] p(l1) l2 = l1.copy() l2.append(4) p(l2) p(l1) l3 = l1.copy() + [5] p(l3) p(l1) l4 = l1 + [5] p(l4) p(l1) """ l1 : [1, 2, 3] l2 : [1, 2, 3, 4] l1 : [1, 2, 3] l3 : [1, 2, 3, 5] l1 : [1, 2, 3] l4 : [1, 2, 3, 5] l1 : [1, 2, 3] """
from debug_log import p class First: def __init__(self, value: int): self.value = value class Second: def __init__(self, value: First): self.value = value # 正しい順序 first = First(1) p(first) second = Second(first) p(second) class Third: def __init__(self, value: Fourth): self.value = value class Fourth: def __init__(self, value: int): self.value = value # 実行順序逆にしないと通らない fourth = Fourth(1) p(fourth) third = Third(fourth) p(third)
from debug_log import p class Cover: def __init__(self, value: int): self.value = value def __repr__(self): return f'Cover({self.value})' l = [1, 2, 3] mapped_l = list(map(Cover, l)) p(mapped_l) ## multi paramater class Cover2: def __init__(self, value: int, value2: str): self.value = value self.value2 = value2 def __repr__(self): return f'Cover2({self.value}, {self.value2})' l2 = [1, 2, 3]
# book2 = Book(book_dict) # p(book2) print('--------- fronze=True ----------') # frozen=Trueの場合のインスタンスの同一性の検証 @dataclass(frozen=True) class Desk: height: int width: int desk1 = Desk(50, 100) desk2 = Desk(50, 100) is_same_desk = desk1 == desk2 # eqはデフォルトでTrueなので、Trueになるはず p(is_same_desk) desk_set = {desk1} p(desk_set) # frozen=Trueにすることで__hash__が実装されるはず desk_set.add(desk2) # 値の同一性で検証されれば追加はできないはず p(desk_set)