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

Unlock This Lesson

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

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Methods and Functions

00:00 Welcome to lesson eight in Object-Oriented Programming in Python versus Java. In this lesson, we’ll explore the nature of Python functions.

00:11 We know from object-oriented programming that a method is used to implement a specific behavior of a class or an object. In Python, we also have something called a function.

00:23 And in this context, we mean a routine that implements a specific task, not attached to any object or class. Java is completely object-oriented. Everything we write has to be a method.

00:39 We don’t have this nature of a function that exists outside of a class or an object. The closest thing that I can think of might be some class methods like we write in, say, the Math class.

00:54 The sqrt() (square root) function really doesn’t have an object to apply to—we just pass a parameter to it—but it has to be defined in a class somewhere, so we make it a static method in the class Math so that we can have something to use to call it.

01:11 While Python is object capable, it doesn’t require you to write things with objects and classes, which means the notion of functions is allowed! So absent of any class, any object, I can create a function! So, let me do it here.

01:31 Let me define a function called say_hi(),

01:37 and we’re just going to print the word "Hi". A simplified version of Python’s “Hello, World” program. And without an object—I’ve not created an object, I don’t have a class—I can call this function simply by referring to it by name. And there it is!

01:56 I can even write this in a Python file or module. I called it hi() here to distinguish it from the say_hi() function I just wrote.

02:08 But if I import this,

02:16 I can call it by simply referring to it directly. And it says Hi as well.

02:24 This isn’t something that we can do in Java. In Java, everything has to be defined in a class. In Python, we can define functions anywhere that we want. In fact, many Python programs exist not making use of a single class or an object.

02:43 Everything they do is done in terms of functions. And so there’s another feature of Python that you don’t get to see in Java. In your next lesson, we’re going to start taking a look at the idea of inheritance and how that’s implemented in Python.

Become a Member to join the conversation.