python - 如何在 python 中设置类变量依赖于其他变量(getter-setter 问题)
问题描述
我想知道是否可以创建一个如下操作的类
a.fullname == jordan lee
a.first == jordan
a.last == lee
when so changes is happening say
a.first = jack
then
a.fullname == jack lee
or set
a.fullname=frank smith
then
a.first == frank
a.last == smith
解决方案
这是使用 getter 和 setter 的“经典”方式:
class Person:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def full_name(self):
return f"{self.first} {self.last}"
@full_name.setter
def full_name(self, full_name):
self.first, self.last = full_name.split()
def __repr__(self):
return f"Person {self.full_name}: first name is {self.first}, last name is {self.last}"
p = Person("John", "Smith")
print(p)
==> Person John Smith: first name is John, last name is Smith
p.first = "Jack"
print(p)
==> Person Jack Smith: first name is Jack, last name is Smith
p.full_name = "Jane Doe"
print(p)
==> Person Jane Doe: first name is Jane, last name is Doe
推荐阅读
- sql - UDL 工作的 SQL 连接问题
- python-3.x - 尝试从命令提示符运行 .py 文件时出错
- php - Joomla 管理面板的替代链接?
- sql-server - 内部加入两次后分组 - 按升序排序
- google-chrome - 是否可以按元素检查网络活动
- xslt - 如何检查节点的至少一个后代是否具有文本内容?
- c# - 使用 Spotify auth 的 ASP.NET 核心重定向失败的外部身份验证服务
- c++ - 如何打印给定 i 和 j 的数字数组,使得 i 的所有元素之和等于 j?
- php - 在 php .sh 文件中执行
- reactjs - 如何在 jest/enzyme 中模拟点击选项卡