首页 > 解决方案 > 如何在 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

标签: python

解决方案


这是使用 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

推荐阅读