Haowei Lou
Haowei Lou

Reputation: 21

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

I want to know is it possible to create a class operating as follows

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

Upvotes: 1

Views: 308

Answers (1)

Roy2012
Roy2012

Reputation: 12493

Here's the 'classic' way of doing it with a getter and a 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

Upvotes: 3

Related Questions