Learning property getter setter in Python


Property is new feature started in Python 2.2. It have great function to return attribute property when class derived from object. For example :

1
2
3
4
5
6
7
8
9
10
11
class Insurance(object):
    def __init__(self):
        self.name = None
        print(self.name)

    def set_name(self):
        self.name = ‘Popel’
        return self.name

a = Insurance()
print(a.set_name())
1
2
print(a.set_name())
# will print "Popel"

To get self.name, we should call method inside derived class, a.set_name().
Then how to change it into attribute ? This why we should know property.

Let see :

1
2
3
4
5
6
7
8
9
10
11
12
class Insurance(object):
    def __init__(self):
        self.name = None
        print(self.name)

    @property
    def set_name(self):
        self.name = ‘Popel’
        return self.name

a = Insurance()
print(a.set_name)

We see that when Insurance() initialized, self.name contain “None”. By using property, we can create attribute called “set_name” and make self.name value into “Popel”.

1
2
print(a.set_name)
# will print "Popel"

Property is great feature in Python that developer should know 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.