2

オブジェクト構成でうまく機能する (Python) スイッチ パターンの設計に問題があります。より具体的には、「entity_id」を引数として取得し(+その他の関連する引数)、オブジェクトとそれに一致するコンポーネントを作成する(おそらく追加の引数を使用して)関数を作成したいと考えています。おもちゃの例はこちら

class Entity:
    def __init__(self,name,animal=None,item=None):
    self.name = name

class Animal: # Animal component
    def __init__(self,legs):
    self.legs = legs

class Item: # Item component
    def __init__(self,quantity):
    self.quantity = quantity

次のようなものが欲しいです:

def place_entity(entity_id,quantity=1):

switch (entity_id):
case 'emu':
    animal_component = Animal(2)
    ent = Entity('Emu', animal_component)
    break

case 'apple':
    item_component = Item(quantity)
    ent = Entity('Apple(s)', item_component )
    break

return(ent)

for ループと if ステートメントを使用して上記を生成するのは簡単ですが、より良い方法はありますか? 簡単にできるはずです

  1. 新しいタイプのエンティティ (バナナ、爪、サメなど) を追加し、
  2. 新しいコンポーネントを追加します(たとえば、エンティティが食用であるかどうか、および含まれるカロリー数を示す食用です)、

あまりにも多くの場所でコードを変更する必要はありません。コンポーネントは追加の引数を必要とする場合があることに注意してください (関数の入力で与えられます)。

switch ステートメントが辞書に置き換えられているのを見たことがありますが、私の実装 (以下) はひどいものでした。別のコンポーネントを追加するには、すべてのエンティティ関数にコードを追加する必要があります!

また、エレガントな方法で引数をコンポーネントに渡す方法もわかりません。この実装では、追加の引数は機能しません。つまり、リンゴのエンティティ (バッチ) を作成したい場合 (数量 = 5 としましょう)、すべてのタイプのエンティティ関数を変更して、数量引数を受け入れるようにする必要があります (使用しない場合でも)。エンティティが作成された後の数量 (if ステートメントを使用する場合、for loop+if ステートメントを使用する可能性があるため、これは賢明ではありません)。

def create_entity(entity_id,quantity=None):

    def emu():
        animal_component = Animal(2)
        entity_data = {'name':'Emu','animal_component':animal_component,
                   'item_component':None}
        return(entity_data)

    def apple(quantity=1):
        item_component = Item(quantity)
        entity_data = {'name':'Apple(s)','animal_component':None,
                   'item_component':item_component}
        return(entity_data)

entity_dict = {'emu':emu,'apple':apple}

entity_data = entity_dict[entity_id]()

ent = Entity(entity_data['name'], animal=entity_data['animal_component'],
             item=entity_data['item_component'])
return(ent)
4

1 に答える 1