Get up to 80 % extra points for free! More info:

Lesson 2 - First object-oriented app in Python - Hello object world

In the previous lesson, Introduction to object-oriented programming in Python, we introduced the object-oriented programming and went over what makes it more efficient than any other programming methodology. We already know that objects have attributes and methods. We also know that to create an object we'd have to create a class first. Remember that a class is a pattern according to which we create instances later.

As we did in the Python basic constructs course we'll create what must always be done when you encounter a new paradigm in programming, a "Hello World" program. A Hello object world program, to be precise!

We'll start by opening IDLE (or any other editor) and creating a new file. We create classes using the class keyword. We'll name our class Greeter. Since there's gonna be a block of code, we write a colon : after the class name. The first line looks like this:

class Greeter:

We name classes using CamelCase, meaning that the first letter in every word in the class name is capitalized and we don't write spaces. The name, of course, shouldn't contain any accent characters, if your native language uses any, you can use them in strings, but never in identifiers. We're going to create a "greeter" object using this class later, which will be able to greet the user. You might've noticed by now that we're treating the program in a different way, for every action, there is some object responsible. In our case, it may seem useless, but in more complex applications it'll prove to be more than worthwhile :)

Next, we'll add a greet() method to the Greeter class, which will be publicly visible and won't return a value or take any parameters.

In Python, we declare methods similarly as functions. We use the def keyword followed by the method's name, which we write in lowercase. In the case the name has more words, we separate them with underscores _. Parentheses with parameters are required. The first required positional argument is self. A "pointer" to the object the method belongs to will be passed through it. In the method body, we'll write code that prints a message to the console.

Our class will now look like this:

class Greeter:

    def greet(self):
        print("Hello object world!")

We could name the first parameter, self, differently, but let's follow established practices.

We'll create an instance of the Greeter class now. Which will be a greeter object that we'll be able to work with. We store objects in variables and use the class name as the data type. Instances usually have the same name as classes, but with the first character in lowercase. Let's declare the variable and then store a new Greeter class instance within it:

greeter = Greeter()

When a new instance is created, the constructor is called. The constructor is a special class method, that's why we write the empty parentheses when creating an instance, we're calling this "creation" method. The constructor usually contains some initialization of the object's internal state, e.g. it initializes the attributes with default values. We haven't declared a constructor in our class, that's why Python created the implicit parameterless constructor. So creating an instance of an object is similar to calling a method.

Since now we have a Greeter class instance in a variable, we can let it greet the user. We'll call the greet() method as greeter.greet(). We will also add input() into the application. So our code will look like this:

class Greeter:

    def greet(self):
        print("Hello object world!")

greeter = Greeter()
greeter.greet()
input()

Let's run the program:

Console application
Hello object world!

We have successfully made our first object-oriented app!

Now let's add a name parameter to our greet() method, so it could greet the user properly:

def greet(self, name):
    print("Hello {0}!".format(name))

The syntax of the method parameter is the same as the syntax of a variable. If we wanted more parameters, we'd separate them with commas. Let's modify the code below the method as well:

greeter = Greeter()
greeter.greet("Carl")
greeter.greet("Peter")
input()

Our code is now in a method and we're able to call it multiple times with different parameters. We don't have to copy "Hello ..." twice. We'll separate our code logically into methods from now.

Console application
Hello Carl!
Hello Peter!

Let's add some attribute to the class, e.g. a text where the greeting will be stored. We declare attributes as variables as well. We then access them using self.. Here's what your class should look like at this point:

def greet(self, name):
    print("{0} {1}!".format(self.text, name))

Since we don't have a constructor method, we have to initialize the text before calling the method which requires it:

greeter = Greeter()
greeter.text = "Hello"
greeter.greet("Carl")
greeter.greet("Peter")
greeter.text = "Hello programmer"
greeter.greet("Richard")
input()

Console application
Hi Carl!
Hi Peter!
Hello programmer Richard!

In object-oriented design, it's not recommended to let each object control the input and output, i.e. printing lots of stuff into the console. Each object should have a single responsibility and shouldn't exceed its purpose. Let's make our object solely responsible for creating the greeting text, and we'll move the printing outside the object. The advantage to designing objects with a single responsibility is that they're then universal and reusable. Our object can only print text to the console now, but we'll change it so the method will only return the text and it'll be up to the recipient to decide what to do with it. Like this we could store greetings into files, print them on websites or process them further.

We use the return keyword to return a value. The return keyword terminates the method and returns the value. Any code in the method's body after the return will not be executed! Let's modify the class:

The greet() method:

def greet(self, name):
    return "{0} {1}!".format(self.text, name)

The main program part will look like this:

greeter = Greeter()
greeter.text = "Hello"
print(greeter.greet("Carl"))
print(greeter.greet("Peter"))
greeter.text = "Hello programmer"
print(greeter.greet("Richard"))
input()

Now, our code follows the guidelines of good OOP and over all programming practices. We will also add comments in our class accordingly. We'll add comments below the class name and the name of each method. We'll use the triple quotes """ to write comments. If we enter the help() command to the interactive console in IDLE (Windows command line doesn't support unicode) and pass the class name as a parameter, it'll display its description and the description of all its methods. A fully documented class might look something like this:

class Greeter:
    """
    A class represents a greeter whose purpose is to greet the user
    """

    def greet(self, name):
        """
        Returns a greeting for the user with a given name
        """
        return "{0} {1}!".format(self.text, name)

Let's check and see that IDLE will actually display the descriptions:

A documented class in Python - Object-Oriented Programming in Python

Great! Our program already has some quality to it, despite it being relatively useless. If you want, you can try to create an object-oriented remake of our console calculator. In the next lesson, RollingDie in Python - Constructors and random numbers, we'll program a simple game. We'll make two objects, warriors, compete in an arena, which will also be an object. See? Now you have something to look forward to! ;-)


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 8x (1.26 kB)
Application includes source codes in language Python

 

Previous article
Introduction to object-oriented programming in Python
All articles in this section
Object-Oriented Programming in Python
Skip article
(not recommended)
RollingDie in Python - Constructors and random numbers
Article has been written for you by David Capka Hartinger
Avatar
User rating:
1 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities