Python #11: Objects & Methods

Objects are values bundled with functions.

When a function works on a value in some way, that’s a method.

greeting = "Hello"
shout = greeting.upper()
whisper = greeting.lower()

print(greeting)
print(shout)
print(whisper)

Output: Hello  HELLO  hello

This code uses a string method ‘upper’ and ‘lower’ to change the capitalization of the greeting ‘hello’. ‘Shout’ and ‘whisper’ are just variable names, the .upper/lower is what prompts the text to print differently.

Most of these elements we’ve been working with are objects. Integers, booleans, lists and tuples, and dictionaries are all objects. Anything that holds a value and can be stored in a variable is an object. Loops and return statements aren’t objects since they don’t hold values by themselves.

Remember how we can add to the end of a list with a +?

my_list = my_list + [4]

There’s also an ‘append’ method that will add values to the end of the list.

my_list.append(4)

You can do this multiple times. The period is what calls the method.

To recap, if you want to cal a method from scratch, you first type a variable name (it can be whatever you want), put an equal sign, type the variable you’re selecting, put a period, type the method you want to use, then close that out with empty parentheses.

And that’ll be it for methods now. I know there’s a lot more, and you can’t really memorize all of them, but it’s important to know how to call and make them work.

I have finished the curriculum for pythonprinciples.com. Next post I’ll be going back over what I struggled with and elaborating on my next steps.

Leave a comment