2017-02-15 7 views
-1

ここにPythonのnoobがあります。私は "テキストアドベンチャー"タイプのゲームに取り組んでいます。私は現在、これらのアイテムのさまざまなデフォルト属性を持つゲームアイテム用のクラスを作成しようとしています。これらの属性の1つは、プレーヤーがこのアイテムを取ることができるかどうかを示すためにブール値の "takeable"になります。私が作成したすべてのアイテムに対してTrueまたはFalsetakeableに割り当てた場合に限り、この作業を行うことができました。私はtakeable=Falseにデフォルトする方法を考え出しましたが、それは "取ることができる"いくつかの項目のためにtakeable=Trueを選択的に渡すことができないようです。Python 3のデフォルトのクラス属性値を上書きする方法は?

class Objects(): 
    """Basic structure of all game objects.""" 

    def __init__(self, item_name, item_description): 
     self.item_name = item_name 
     self.item_description = item_description 
     self.takeable = False 


items = { 
    "main_room_table": Objects("Wooden table", "A large wooden table with items scatter atop its surface."), 
    "main_room_key": Objects("Small brass key", "A small brass skeleton key. What could it unlock?", takeable=True) 

これはPythonが別の引数を期待していないときに、私は、引数takeable=Trueを渡しているので、TypeError: __init__() got an unexpected keyword argument 'takeable'が、私はこれが起こっている理解してしまいます。

クラスインスタンスの作成時にこのようなデフォルト値をオーバーライドする方法はありますか?私はちょうどtakeableの新しい "アイテム"インスタンスを作成するたびに渡されるブール値を要求することができますが、値がデフォルトになり、クラスインスタンスの作成でそれを上書きできる方法があるようです。

答えて

0

デフォルト値は、init定義内ではなく、引数に割り当てられます。

class Objects(): 
    """Basic structure of all game objects.""" 

    def __init__(self, item_name, item_description, takeable=False): 
     self.item_name = item_name 
     self.item_description = item_description 
     self.takeable = takeable 


items = { 
    "main_room_table": Objects("Wooden table", "A large wooden table with items scatter atop its surface."), 
    "main_room_key": Objects("Small brass key", "A small brass skeleton key. What could it unlock?", takeable=True), 
} 

もう一つの方法は、作成後にそれを設定されていたであろうが、それはこれは私が必要なものであるitems["main_room_key"].takeable = True

+0

dict外でそれを行うには、それを必要とします。私は "takeable = False"をどこに置くべきか誤解した。ご回答いただきありがとうございます。 – CrashTestDummy

0

__init__takeableパラメータを受け入れません。あなたはそれオプションの引数(与えられていない場合は、Falseに不履行)することができます:

def __init__(self, item_name, item_description, takeable=False): 
    [...] 
    self.takeable = takeable 
0

あなたは文字通り、デフォルト引数を記述している:

class Objects(): 
    """Basic structure of all game objects.""" 

    def __init__(self, item_name, item_description, takeable=False): 
     self.item_name = item_name 
     self.item_description = item_description 
     self.takeable = takeable 

今あなたが選択するか、ではない、としてtakeableを提供することができます値であり、そうでなければ、値はFalseです。

関連する問題