Python Object Methods
A method is a function defined inside a class. A method works on the object it is called on.
A method that reads self
bark() is a function inside the class. It reads the name from self.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return self.name + " says woof!"
buddy = Dog("Buddy", 3)
print(buddy.bark())A method that changes self
birthday() adds one to the age. The change stays on the object.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def birthday(self):
self.age = self.age + 1
buddy = Dog("Buddy", 3)
buddy.birthday()
print(buddy.age)A friendly print with __str__
__str__ returns the text to show. print() uses that text for the object.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return self.name + " is " + str(self.age) + " years old"
buddy = Dog("Buddy", 3)
print(buddy)Example
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return self.name + " says woof!"
def birthday(self):
self.age = self.age + 1
def __str__(self):
return self.name + " is " + str(self.age) + " years old"
buddy = Dog("Buddy", 3)
print(buddy.bark())
print(buddy)
buddy.birthday()
print(buddy)Key points
- Method: a function defined inside a class
- Use dot notation to call a method, like buddy.bark()
- self gives a method the object it was called on
- __str__: a special method that returns text for print()
In this example, Dog gains three methods. bark() reads the name from self and returns a short line. __str__ returns friendly text about the dog. So print(buddy) shows that text, not an address. birthday() then adds one to the age on self. The last print line shows the new age, 4.
Note
Without __str__, print() shows a memory address instead.
That address changes each run, so it helps no one.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does the __str__ method do?