【问题标题】:Method that can alter multiple properties within an object in Python [duplicate]可以在Python中更改对象内多个属性的方法[重复]
【发布时间】:2020-10-12 21:37:03
【问题描述】:

我正在尝试使用对象中的方法来选择性地更改该对象的特定属性。我一直无法弄清楚如何让该方法识别我传递给它的值作为指示预先存在的属性。

class Attributes(object):
        def __init__(self, strength, speed):
            self.strength = strength
            self.speed = speed
        
        def increase(self, attribute, amount):
        
            self.attribute += amount
       
    You = Attributes(1, 2)
    

    You.increase(strength, 5)

    print(You.strength)    

控制台告诉我“强度未定义”。

将值返回给对象是我可能做错的另一件事,所以那里的任何建议也会有所帮助。谢谢

【问题讨论】:

标签: python object methods properties


【解决方案1】:

您可以利用内置函数getattrsetattr 与对象的属性进行交互。这是一个例子:

class Attributes(object):
    def __init__(self, strength, speed):
        self.strength = strength
        self.speed = speed

    def increase(self, attribute, amount):
        value = getattr(self, attribute)
        value += amount
        setattr(self, attribute, value)


you = Attributes(1, 2)
you.increase("strength", 5)
print(you.strength)  # outputs: 6

【讨论】:

    【解决方案2】:

    变量声明的位置会影响其范围Attributes 构造函数__init__strength 参数具有本地范围,这意味着它只能在__init__ 方法中可见。要了解有关范围的更多信息,请参阅https://docs.python.org/3.3/reference/executionmodel.html

    养成使用setattrgetattr 内置函数的习惯将被视为不好的做法,如下所述:Can the usage of `setattr` (and `getattr`) be considered as bad practice?

    此外,SOLID 设计原则中的接口隔离原则 (ISP) 旨在使软件设计更易于理解、灵活和可维护,该原则指出,大型接口应拆分为更小、更具体的接口,以便“客户”只有了解他们感兴趣的方法。 ISP 旨在保持系统解耦,从而更容易重构、更改和重新部署。因此,与其编写一种负责增加所有属性的方法,我建议将该方法拆分为更小的“角色接口”以提高代码质量。

    可以补充一点,根据 PEP 8 -- Python 代码样式指南,变量名应该小写,单词之间用下划线分隔以提高可读性 (https://www.python.org/dev/peps/pep-0008/)。此外,使类型变量具有自描述性和内聚性是一种很好的做法。

    为此,我建议编写不同的方法来增加强度和速度,将Attributes 类的名称更改为Person 并将变量名称You 设为小写,如下所示:

    class Person(object):
        def __init__(self, strength, speed):
            self.strength = strength
            self.speed = speed
        
        def increaseStrength(self, amount):
            self.strength += amount
    
        def increaseSpeed(self, amount):
            self.speed += amount
       
    you = Person(1, 2)
    
    
    you.increaseStrength(5)
    
    print(you.strength)   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2019-05-06
      相关资源
      最近更新 更多