简体   繁体   中英

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

  • 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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM