Instance methods


Regular functions (methods) defined in a class are "instance methods". They can only be called on "instance objects" and not on the "class object" as see in the 3rd example.
The attributes created with "self.something = value" belong to the individual instance object.

examples/oop/mydate1/mydate.py
class Date:
    def __init__(self, Year, Month, Day):
        self.year  = Year
        self.month = Month
        self.day   = Day

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

    def set_date(self, y, m, d):
        self.year = y
        self.month = m
        self.day = d

examples/oop/mydate1/run.py
from mydate import Date

d = Date(2013, 11, 22)
print(d)

# We can call it on the instance
d.set_date(2014, 1, 27)
print(d)

# If we call it on the class, we need to pass an instance.
# Not what you would normally do.
Date.set_date(d, 2000, 2, 1)
print(d)


# If we call it on the class, we get an error
Date.set_date(1999, 2, 1)

set_date is an instance method. We cannot properly call it on a class.


Date(2013, 11, 22)
Date(2014, 1, 27)
Date(2000, 2, 1)
Traceback (most recent call last):
  File "run.py", line 17, in <module>
    Date.set_date(1999, 2, 1)
TypeError: set_date() missing 1 required positional argument: 'd'