簡體   English   中英

如何設置 class 變量依賴於 python 中的其他變量(getter-setter 問題)

[英]How to set class variable rely on others in python (a getter-setter question)

我想知道是否可以創建一個 class 操作如下

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM