[英]Python Nested functions within a class that update the class instance
我有一个类,我们称之为 EmployeeProfile。 它收集了大量关于一个人的数据。
我希望能够使用函数更新类中的特定数据。
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)
我希望能够扩展更新功能,以便可以更新类的任何属性。
你有很多选择。 其中一些包括使用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
最好,但属性名称是静态的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.