Python class 中更新 class 实例的嵌套函数

Python Nested functions within a class that update the class instance

我有一个 class 我们称它为 EmployeeProfile。 那收集了一堆关于一个人的数据。

我希望能够使用函数更新 class 中的特定数据。

class EmployeeProfile:
def __init__(self, profile):
    self.displayname = profile.get('displayName')
    self.email = profile.get('email')
    self.firstname = profile.get('firstName')
    self.surname = profile.get('surname')
    self.fullname = profile.get('fullName')
    self.costcode = profile.get('work').get('custom')

def update(self, operation, value):

    def manageremail(value):
        self.manageremail = value

    def costline(value):
        self.costline = value

有没有办法使用一个更新函数来指定要更新的属性,以及 运行 相关的嵌套函数?

class Ted()
Ted.update('manageremail', 'noreply@me.com)

我希望能够扩展更新功能,以便我可以更新 class 的任何属性。

你有很多选择。其中一些包括使用 setattr()、更新 __dict__ 或使用自定义词典:

class EmployeeProfile:
  ATTRIBUTES = {"email", "displayname"}
  def __init__(self, profile):
    self.displayname = profile.get('displayName')
    self.email = profile.get('email')
    ...
  def update(self, attribute, value):
      if attribute not in self.ATTRIBUTES:
          raise ValueError(f"Invalid attribute {attribute!r}")
      setattr(self, attribute, value)

employee = EmployeeProfile({})

# All of these are practically equivalent
employee.update("email", "stuff@stuff")
employee.__dict__["email"] = "stuff@stuff2"
setattr(employee, "email", "stuff@stuff3")  # <--- Personally I'd choose this.
employee.email = "stuff@stuff4"  # <---- Or this.

一些随机点:

  • 自定义 update() 函数允许您设置特定属性 是可更新的,其余的不是,或者做更复杂的逻辑 不使用 @property.

  • setattr 非常简单,如果您需要,稍后可以与 @property 一起使用。

  • 使用 __dict__.update() 允许您一次更新多个值,即 employee.update({"email": "rawr@rawr", "displayname": "John"}),但不允许 属性 装饰器。

  • .email 最好,但属性名称是静态的。