Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@mio_k

PythonでFactoyMethod

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

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
0
Help us understand the problem. What are the problem?