Help us understand the problem. What is going on with this article?

PythonでFactoyMethod

More than 1 year has passed since last update.

FactoryMethodが便利だったのでメモ。FactoryMethodはデザインパターンの一つで、一般的なインスタンス生成とは異なる方法でインスタンスを生成できます。具体的にはstrを渡してインスタンスが生成できるので、いろいろ使える場面がある気がする。

使い方の例

class Dog:
    def bark(self):
        print('ワンワン')

class Cat:
    def bark(self):
        print('ニャーニャー')

def pet_shop(pet):
    # これがFactoryMethod
    pets = dict(Dog=Dog, Cat=Cat)
    return pets[pet]()

my_dog = pet_shop('Dog')
my_dog.bark()
# >> ワンワン
my_cat = pet_shop('Cat')
my_cat.bark()
# >> ニャーニャー

参考ページ
python-patterns

mio_k
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした