Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Giving Your Classes Behavior With Methods

Resource mentioned in this lesson: Python’s Instance, Class, and Static Methods Demystified

00:00 Your classes don’t have to be static data containers. You can customize their behavior through the use of methods. Methods are functions defined within a class.

00:09 Instance methods define behaviors for class instances. They can be called on class instances using the dot accessor, and they provide encapsulation by bundling functionality with data. You define instance methods in the class body with the def keyword.

00:25 You could take the Crew class defined before and add a method like this. Within the class body after __init__(), you can add a description() method, def description: taking in the parameter self. Return the f-string f"{self.name} is {self.age} years old." The resulting method can be called on Crew instances using the dot accessor, like crew_instance.description() and when called, self takes on the value of the instance calling the method just like with __init__().

00:52 Because self is an instance of Crew, you can access its instance attributes of name and age. And note how these are referred to as instance methods.

01:01 That’s because there’s actually a few different kinds of methods you can define in classes. They go beyond the scope of this course, but here’s a recommendation for your reading list: Python’s Instance, Class, and Static Methods Demystified.

01:14 Now open up the code editor of your choice and we’ll look at instance methods in more detail.

01:20 Here in VS Code, we’re starting with the Starship class you defined in the previous lesson. You’ll be adding two methods: description(), which will return a string describing the instance and set_destination(), which returns a string description of the action. def description: taking in the parameter self. Return the f-string f"{self.ship_type} - {self.name}".

01:45 def set_destination taking in the parameter self and destination. Return the f-string f"{self.name} sets a course for {destination}."

01:59 Now save, open up the terminal, and open the REPL. Because this terminal is running in the same directory as starship.py, you can import classes directly, like so: from starship import Starship and create a ship: enterprise = Starship( "Enterprise", 430)

02:19 and try out that description() method. And remember, because self is the only parameter, you actually pass nothing when you call it. enterprise.description() returns 'Exploration vessel - Enterprise'. Now try set_destination().

02:32 This takes an argument, the destination. Try

02:36 enterprise.set_destination("Earth"), 'Enterprise sets a course for Earth' Or another one, enterprise.set_destination("Vulcan") 'Enterprise sets a course for Vulcan'.

02:49 Okay, pretty cool, but there’s something not entirely Pythonic about that description() method. It’s useful for classes to provide a string description with info about the class, but as Python developers, normally we’d want to use the print() function to see it.

03:04 For example, if you have a list with some contents like a list of ships with the strings "Enterprise", "TARDIS" and "Millennium Falcon".

03:14 If you print that list, you should see its contents, right? print(ships) and the result is 'Enterprise', 'TARDIS' and 'Millennium Falcon'.

03:22 But right now, if you print our Starship enterprise, you get the default description: print(enterprise) <starship.Starship object> at some memory address.

03:32 Turns out this is also a behavior you can change in your class.

03:36 Exit the REPL for now, and edit starship.py. In fact, all you really need to do is change the name of description from description to __str__ for string.

03:48 This is another special method, and it controls what will be displayed when the class instances are passed to the print() function. The important thing is that it returns a string, which description() already did.

04:00 So save and go back to the REPL.

04:05 from starship import Starship enterprise = Starship( passing in "Enterprise", 430) and print(enterprise)

04:17 "Exploration Vessel - Enterprise", ta-da. You can see why it’s called a magic method, and this is also a great example of the principle of abstraction.

04:27 Users of the Starship class don’t need to know anything about Starship internals or the print() function’s internals to use them together to get a useful output.

04:36 Now that the Starship class has a little more going on, maybe you’re already thinking about other kinds of space vessels that could exist, that might share functionality with Starship, but perhaps be more specialized.

04:48 Yes? Then it’s the perfect time to talk about inheritance. See you in the next lesson.

Become a Member to join the conversation.