User Tools

Site Tools


python:python_misc:properties_in_python_classes

Properties in Python

Good writeups:

class ClickerCounter():
    def __init__(self, upper):
        self.__count = 0     # instance variable for storing the count
        self.__limit = upper # instance variable for storing the limit
 
    def click(self):
        """
        Advance the count by one and reset if over the upper limit.
        """
        self.__count += 1
        # wrap the count if over the limit
        if self.__count > self.__limit:  
            self.__count = 0
 
    def reset(self):
        """Reset the counter."""
        self.__count = 0
 
    @property
    def count(self):
        return self.__count
 
    @property
    def limit(self):
        return self.__limit
 
    @limit.setter
    def limit(self, l):
        """Set a new count limit."""
        if l > 0:
            self.__limit = l
        else:
            print('Invalid new limit:', l)
 
c = ClickerCounter(100)
 
c.click()
c.click()
print(c.count)  # 2
print(c.limit)  # 100
 
c.limit = 1000
print(c.limit)  # 1000
 
c.limit = 0
print(c.limit)  # 1000
python/python_misc/properties_in_python_classes.txt · Last modified: 2019/06/21 23:16 by mithat