How to write getter-setter methods for a private attribute in python class?

2.2k views Asked by At
  • Operating System: Windows 10, 64 bit
  • Editor: VSCode 1.56.2
  • Python: 3.9.0

I have a class with year property.

When I want to private this property, it seems that get and set functions that are written using @property and @year.setter decorators don't work.

class Ab():
    def __init__(self, year):
        self.__year = year
        print(self.__year)

    @property
    def year(self):
        return self.__year

    @year.setter
    def year(self, y):
        if y < 8:
            self.__year = 0
        else:
            self.__year = y


a = Ab(5)

Actual output: 5

Expected output: 0

I'm new in python, so thanks in advance for any helps.

2

There are 2 answers

2
Teejay Bruno On

You need to reference the the setter in your __init__-- not the dunder private property.

class Ab():
    def __init__(self, year):
        self.year = year
        print(self.__year)
7
Lucas Ng On

You never actually modified Ab.year:

class Ab():
    def __init__(self, year):
        self.__year = year
        self.year = year # <-- this needs to be here
        print(self.__year)

    @property
    def year(self):
        return self.__year

    @year.setter
    def year(self, y):
        if y < 8:
            self.__year = 0
        else:
            self.__year = y
a = Ab(5)
>>> 0

Btw it's a bad idea to use double leading underscores unless you explicitly want name-mangling.