1

指定された引数に基づいてクラス属性を変更しようとしています。私はPythonを始めたばかりですが、辞書を使わずにそれを行う方法を見つけることができないようです. これを行うためのpythonicの方法はありますか?以下の例を参照してください

class Ship:

    def __init__(self, name):
        self.name = name
        ship_type = {"schooner": [50, 30, 18],
            "galleon": [30, 14, 14]
        }
        self.max_weight = ship_type[name][0]
        self.speed = ship_type[name][1]
        self.poopdeck = ship_type[name][2]

    def upgrade(self, attribute, value):
        self.attribute += value


Someship.ship.upgrade(speed, 10)

属性ごとに異なるメソッドを書き出すことができますが、このようなものが必要であるかのように感じます。
これがすでに回答されている場合は事前にお詫び申し上げますが、ある場合は正しく言えませんでした。

4

2 に答える 2

0

update メソッドを変更して、組み込み関数 hasattr()およびを使用して既存の属性を更新setattr()しますgetattr()

def upgrade(self, attribute, value):
  if hasattr(self, attribute):
    setattr(self, attribute, getattr(self, attribute) + value )
  else:
    raise AttributeError("Can't upgrade non-existent attribute '{}'.".format(attribute))

__dict__インスタンスのセットアップを簡単にするために、属性も使用することに注意してください。

class Ship:
  # types is a class variable, and will be the same for all instances,
  # and can be referred to by using the class. ie `Ship.types`
  types = {
    "schooner": {'weight':50, 'speed':30, 'poopdeck':18},
    "galleon": {'weight':30, 'speed':14, 'poopdeck':14},
    "default": {'weight':11, 'speed':11, 'poopdeck':11}
  }
  def __init__(self, name):
    self.name = name
    # we update the instance dictionary with values from the class description of ships
    # this means that instance.speed will now be set, for example.
    if name in Ship.types:
      self.__dict__.update(Ship.types[name]) 
    else:
      self.__dict__.update(Ship.types["default"])

  def upgrade(self, attribute, value):
    if hasattr(self, attribute):
      setattr(self, attribute, getattr(self, attribute) + value )
    else:
      raise AttributeError("Can't upgrade non-existent attribute '{}'.".format(attribute))

ship = Ship("schooner")
print(ship.speed) #=> 30
ship.upgrade("speed", 10)
print(ship.speed) #=> 40
于 2013-06-19T20:46:38.177 に答える
0

setattrandgetattr関数を探しています。メソッドは次のupgradeように実装できます

def upgrade(self, attribute, value):
    setattr(self, attribute, getattr(self, attribute) + value )
于 2013-06-19T20:25:54.600 に答える