Static methods


Static methods are used when no "class-object" and no "instance-object" is required. They are called on the class-object, but they don't receive it as a parameter.

examples/oop/static_method/mydate.py
class Date(object):
    def __init__(self, Year, Month, Day):
        if not Date.is_valid_date(Year, Month, Day):
            raise Exception('Invalid date')
        self.year  = Year
        self.month = Month
        self.day   = Day

    def __str__(self):
        return 'Date({}, {}, {})'.format(self.year, self.month, self.day)

    @staticmethod
    def is_valid_date(year, month, day):
        if 0 <= year <= 3000 and  1 <= month <= 12 and 1 <= day <= 31:
            return True
        else:
            return False

examples/oop/static_method/run.py
import mydate

a = mydate.Date(2013, 10, 20)
print(a)

print(mydate.Date.is_valid_date(2013, 10, 40))

b = mydate.Date(2013, 13, 20)

Date(2013, 10, 20)
False
Traceback (most recent call last):
  File "run.py", line 8, in <module>
    b = mydate.Date(2013, 13, 20)
  File "static_method/mydate.py", line 4, in __init__
    raise Exception('Invalid date')
Exception: Invalid date