LoginSignup
2
2

More than 5 years have passed since last update.

pythonでcase class

Posted at

Scalaでcase classというのがあります。
newする際に入れた引数とその名前でimmutableオブジェクトを作ってくれるやつです。

便利なのでpythonでもcase classっぽいもの作りたいなー、と思ってやってみました

def caseclass(args):

    class _Case(object):
        def __init__(self, kwargs):
            self._initwargs = kwargs


        def _type_check(self, key, value):
            if isinstance(value, self._initwargs[key]) is False:
                raise TypeError;

        def init(self, **kwargs):
            [self._type_check(key, kwargs[key])  for key in kwargs]
            self._kwargs = kwargs

        def getattr(self, name):
            return self._kwargs[name]

        def setattr(self, name, value):
            raise TypeError;



    def case(klass):
        _case = _Case(args)
        krass = type(klass.__name__, klass.__bases__,
                     {
                "__getattr__":_case.getattr,
                "__setattr__":_case.setattr,
                "__init__":_case.init
                })

        return krass

    return case

で、使い方はcaseclassをデコレータとして使います

#{引数:引数の型}という形式の辞書インスタンスを引数にします
@caseclass({'foo':str, 'bar':int})
class Hoge(object):pass

hoge = Hoge(foo = "hello", bar = 1)
print(hoge.foo) # "hello"と出力
print(hoge.bar) # 1と出力
hoge.num = 1 # SetしようとするとTypeErrorが飛びます

fuga = Hoge(dosukoi = "nokotta") #と、定義されてない引数を指定してもErrorが飛びます

もしかしたら、もっといいやり方あるかも

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2