0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python で静的メソッドベース API っぽいのを実現するメモ

Posted at

背景

インスタンスでメソッド呼んだりするのが好きくない.
(インスタンスの内部状態に依存しないようにしたい)

bora = Bora()
dora = bora.Dora("test")

みたいなの, 好きくない.

インスタンスをメソッドで作る API を Python で実現したい

obj = Bora.Dora.NewObject("test")

みたいな? 名前空間(namespace)で機能を切り分けして.

名前空間の階層?

ディレクトリを作ればいいですが, ファイルが増えて面倒です.

とりあえず inner class でいけるっぽい.


class Bora:
   class Dora:
     ...

class method

静的メソッドは @staticmethod, @classmethod でいけます.
ここでは @classmethod 使います.

class Bora:
   class Dora:
     @classmethod
     def NewObject(cls, name: str):
       obj = cls()
       obj.name = name
       return obj

Voila!

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?