修改变量类属性

时间:2013-06-19 20:21:07

标签: class python-3.x

我正在尝试根据给定的参数修改类属性。我刚刚进入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)

我可以为每个属性写出不同的方法,但我觉得好像必须有这样的东西。
如果已经回答,我会提前道歉,但如果有的话我无法说出来。

2 个答案:

答案 0 :(得分:0)

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

def upgrade(self, attribute, value):
    setattr(self, attribute, getattr(self, attribute) + value )

答案 1 :(得分:0)

使用builtin functions 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
相关问题