5
4

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のクラスメソッドで自身の型を返す方法

Posted at

概要

  • 自身のインスタンスを返すクラスメソッドを作成する際、下記のように返り値の型をクォーテーションで囲む必要がある
@classmethod
def create(cls,
            name: str,
            age: int
            ) -> 'User':
  • これはファイルの先頭でfrom __future__ import annotationsを呼ぶことで解消できる
from __future__ import annotations
from dataclasses import dataclass


@dataclass
class User:
    name: str
    name_in_lowercase: str
    name_in_uppercase: str
    age: int

    @classmethod
    def create(cls,
               name: str,
               age: int
               ) -> User:
        return User(name=name,
                    name_in_lowercase=name.lower(),
                    name_in_uppercase=name.upper(),
                    age=age)

    def print_description(self):
        print(f'name: {self.name}\nname_in_lowercase: {self.name_in_lowercase}\nname_in_uppercase: {self.name_in_uppercase}\nage: {self.age}')


def main():
    user = User.create(name="John Titor", age=36)
    user.print_description()


if __name__ == "__main__":
    main()

  • 実行結果
name: John Titor
name_in_lowercase: john titor
name_in_uppercase: JOHN TITOR
age: 36

参考

5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?