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

您正在寻找setattrgetattr功能。您的upgrade方法可以实现为

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

使用内置函数 更改更新方法以更新现有属性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 回答