Home > Enterprise >  Python Nested functions within a class that update the class instance
Python Nested functions within a class that update the class instance

Time:05-18

I have a class lets call it EmployeeProfile. That collects a bunch of data about a person.

I would like to be able to update specific data within the class using a function.

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

Is there a way to use one update function to specify what attribute to update, and run the relevant nested function?

class Ted()
Ted.update('manageremail', '[email protected])

I would like to be able to expand on the update function so I can update any of the attributes of the class.

CodePudding user response:

You have plenty of options. Some of them include using setattr(), updating the __dict__ or using a custom dictionary:

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.

Some random points:

  • A custom update() function allows you to set specific attributes that are updatable and the rest aren't, or do more complex logic without using @property.

  • setattr is very simple and plays well with @property later on should you need.

  • Using __dict__.update() allows you to update multiple values at once, i.e employee.update({"email": "rawr@rawr", "displayname": "John"}), but doesn't allow property decorators.

  • .email is best but the attribute name is static.

  • Related